Use EF changetracker to manually get set of changes?

George Mauer picture George Mauer · May 14, 2015 · Viewed 10.7k times · Source

If I load up an entity, make some changes, and then go to save it, EF generates an update statement.

This must mean that at some point something (presumably the change tracker) is navigating the loaded object hierarchy and generating a list of (entity, property, value) that changed. For an unrelated bit of infrastructure I need to basically diff object graphs in a similar fashion. I'm thinking that I should be able to reuse the same mechanism.

So that's the question - can I do this? Can I query changes to a particular entity or even to the entire object graph? How?

Answer

user2697817 picture user2697817 · May 14, 2015

You could use the context's DbChangeTracker which returns an IEnumerable<DbEntityEntry>. You could then loop over these comparing the CurrentValues with the OriginalValues. The original values are the values from the last query to the db.

var modifiedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified);
foreach (DbEntityEntry entity in modifiedEntries)
{
    foreach (var propName in entity.CurrentValues.PropertyNames)
    {
        var current = entity.CurrentValues[propName];
        var original = entity.OriginalValues[propName];
    }
}