Entity Framework DbContext SaveChanges() OriginalValue Incorrect

£可爱£侵袭症+ 提交于 2019-11-27 15:41:53
Arthur Vickers

When EF retrieves an entity from the database it takes a snapshot of the original values for all properties of that entity. Later, as changes are made to the values of these properties the original values will remain the same while the current values change.

However, for this to happen EF needs to be tracking the entity throughout the process. In a web or other n-tier application, typically the values are sent to the client and the context used to query the entity is disposed. This means that the entity is now no longer being tracked by EF. This is fine and good practice.

Once the application posts back the entity is reconstructed using values from the client and then re-attached to the context and set into a Modified state. However, by default the only values that come back from the client are the current values. The original values are lost. Usually this doesn't matter unless you are doing optimistic concurrency or want to be very careful about only updating values that have really changed. In these cases the original values should also be sent to the client (usually as hidden fields in a web app) and then re-applied as the original values as a part of the attach process. This was not happening in the example above and this is why the original values were not showing as expected.

Mike Munro

If you change

dbEntry.OriginalValues.GetValue<object>(propertyName);

to

dbEntry.GetDatabaseValues().GetValue<object>(propertyName);

then that works.

I got this error when i override SaveChanges in context As follows

public override int SaveChanges()
    {
        var changeInfo = ChangeTracker.Entries()
            .Select(t => new {
                Original = t.OriginalValues.PropertyNames.ToDictionary(pn => pn, pn => t.OriginalValues[pn]),
                Current = t.CurrentValues.PropertyNames.ToDictionary(pn => pn, pn => t.CurrentValues[pn]),
            }).ToList();
        return base.SaveChanges();
    }

and when I cleared it fixed!

ChangeTracker.Entries().ToList() in SaveChanges is wrong...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!