I've read multiple posts about how to implement an audit log using entity framework. I currently have the audit logic embedded in the SaveChanges
method in the DbContext
. Please keep in mind that the code below is an EF4/5 implementation and I'm preparing to update to EF6.
namespace Database {
public class AuditDetails {
public string RemoteHost { get; set; }
public string RevisionUser { get; set; }
public string RevisionNotes { get; set; }
public DateTime RevisionDateTime { get; set; }
}
public class MyContext : DbContext {
// ... Unrelated overrides here ... //
public void SaveChanges(AuditDetails auditDetails) {
var saveCount = ProcessConcurrency();
var items = ChangeTracker.Entries<MyEntity>().ToList();
if (saveCount <= 0 || items == null || !items.Any() || auditDetails == null) return;
foreach (var item in items.Select(entityEntry => entityEntry.Entity).Where(i => i != null)) {
// ... create audit log using AuditDetails values ... //
}
// ... and call base.SaveChanges() ... //
}
}
}
So the questions would be:
- Is there a benefit to moving this to a
SavingChanges
event handler? Or possibly split the functionality to use both? - Does the
AuditDetails
information preclude usingSavingChanges
? - I do not have an override for
SaveChanges
that accepts the Boolean argument for use in transactions. How would adding that change the solution?
In Summary:
- When would you override/implement
SaveChanges
and when/why would you prefer to use aSavingChanges
event handler?