Use EF changetracker to manually get set of changes?

c# change-tracking entity-framework

Question

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?

1
4
5/13/2015 11:51:11 PM

Accepted Answer

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];
    }
}
14
12/19/2019 8:33:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow