Entity Framework DbContext SaveChanges() OriginalValue Incorrect

前端 未结 5 980
孤街浪徒
孤街浪徒 2020-12-03 21:51

I am trying to implement an AuditLog using EF 4.1, by overriding the SaveChanges() method as discussed in the following places:

  • http://jmdority.wordpress.com/2
5条回答
  •  情话喂你
    2020-12-03 22:39

    The problem is not in the code you show here. The issue is that how you track entities. If you just create an entity object and calls Update on it EF framework just overwrite the existing value in db ( provided you supplied correct ID ). That is done for efficiency. So if you do:

    var company = new Company{Id = mySuppliedId, Name = newname};
    Context.Companies.Update(company);
    Context.SaveChanges(); 
    

    EF will go directly to DB in one shot and update all properties on the entity, without bringing anything back first. So it has no way of knowing the original values. If you change the code in your logic to something like:

    var company = Context.Companies.Where(c=>c.Id == mySuppliedId).FirstOrDefault();
    company.Name = newName;
    Context.SaveChanges() 
    

    Then your ChangeTracker code you showed above all of sudden starts working, as EF brought the data from DB first. It is however less efficient as you make and extra query.

提交回复
热议问题