I am trying to overirde SaveChanges() method of DBContext in my MVC6 application with EF6. My requirement is to track the modified property of all entities and log in database.
The problem is that originalValue and currentValue both gives me updated value. I can't get the old values. Please suggest what I am doing wrong. I referred below link.
http://www.exceptionnotfound.net/entity-change-tracking-using-dbcontext-in-entity-framework-6/
public override int SaveChanges()
{
var modifiedEntities = ChangeTracker.Entries()
.Where(p => p.State == EntityState.Modified).ToList();
var now = DateTime.UtcNow;
List<ChangeLog> ChangeLogs = new List<ChangeLog>();
foreach (var change in modifiedEntities)
{
var entityName = change.Entity.GetType().Name;
var primaryKey = GetPrimaryKeyValue(change);
foreach (var prop in change.OriginalValues.PropertyNames)
{
var originalValue = change.OriginalValues[prop].ToString();
var currentValue = change.CurrentValues[prop].ToString();
if (originalValue != currentValue)
{
//Save log
}
}
}
return base.SaveChanges();
}