Created
November 4, 2014 15:58
-
-
Save EmadMokhtar/33157ebf531681f6474c to your computer and use it in GitHub Desktop.
AuditTrailWithUsername
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Data.Entity; | |
using System.Data.Entity.Infrastructure; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Web; | |
namespace DataModel | |
{ | |
enum EntityCommandType | |
{ | |
Insert, | |
Update, | |
Delete | |
} | |
public partial class WebTimeTelEntities : DbContext | |
{ | |
public int SaveChanges(string username) | |
{ | |
List<AuditLog> list = new List<AuditLog>(); | |
var entries = from e in this.ChangeTracker.Entries() | |
where e.State != EntityState.Unchanged | |
select e; | |
foreach (var entry in entries) | |
{ | |
switch (entry.State) | |
{ | |
case EntityState.Added: | |
list.AddRange(CreateAuditLog(entry, EntityCommandType.Insert,username)); | |
break; | |
case EntityState.Modified: | |
list.AddRange(CreateAuditLog(entry, EntityCommandType.Update,username)); | |
break; | |
case EntityState.Deleted: | |
list.AddRange(CreateAuditLog(entry, EntityCommandType.Delete, username)); | |
break; | |
} | |
} | |
foreach (AuditLog auditLog in list) | |
{ | |
this.AuditLogs.Add(auditLog); | |
} | |
return this.SaveChanges(); | |
} | |
private List<AuditLog> CreateAuditLog(DbEntityEntry entry, EntityCommandType commandType, string username) | |
{ | |
List<AuditLog> list = new List<AuditLog>(); | |
foreach (var propertyName in entry.CurrentValues.PropertyNames) | |
{ | |
var auditLog = new AuditLog | |
{ | |
Action = Enum.GetName(typeof(EntityCommandType), commandType), | |
TableName = entry.Entity.GetType().Name, | |
TimeStamp = DateTime.Now, | |
KeyField = propertyName, | |
NewValue = entry.CurrentValues[propertyName].ToString(), | |
OldValue = commandType == EntityCommandType.Update ? entry.GetDatabaseValues()[propertyName].ToString() : null, | |
Username = username | |
}; | |
list.Add(auditLog); | |
} | |
return list; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment