I was implementing audit in my EF 6 database by adding a ModifiedDate property in the entity base and tried to override SaveChanges() by adding the below code (Taken from https://stackoverflow.com/a/6282472/82152)
public class Session : ISession
{
public DbContext _context;
public Session(DbContext context)
{
_context = context;
}
. . .
public int SaveChanges()
{
var context = ((IObjectContextAdapter)_context).ObjectContext;
var objectStateEntries =
from e in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified)
where
e.IsRelationship == false &&
e.Entity != null &&
typeof(ModelBase).IsAssignableFrom(e.Entity.GetType())
select e;
foreach (var entry in objectStateEntries)
{
var modelBase = entry.Entity as ModelBase;
modelBase.LastModifiedDate = DateTime.Now;
}
return _context.SaveChanges();
}
After I changed one of the entity properties, and called SaveChanges - I could see that none of the objectStateEntries were marked as EntityState.Modified. It was all marked as EntityState.Unchanged.
Now after doing some reading, I changed my SaveChanges method to do context.DetectChanges(); after the first line - and it all worked. I tested a case where the entity property changed and another case where the entity property did not change, and it worked perfectly.
Now my concern is
- Although my current solution works, would it take a performance hit ?
- Why doesn't context.Configuration.AutoDetectChangesEnabled=true do the job of tracking the change automatically from property changes ?