Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use EF changetracker to manually get set of changes?

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?

like image 775
George Mauer Avatar asked May 13 '15 23:05

George Mauer


People also ask

How do I use ChangeTracker in EF core?

See Change Detection and Notifications for more information on how EF Core automatically detects changes like this. Call ChangeTracker. HasChanges() to determine whether any changes have been made that will cause SaveChanges to make updates to the database. If HasChanges return false, then SaveChanges will be a no-op.

How do you get entities back from a query without getting tracked by the context?

The AsNoTracking() extension method returns a new query and returned entities do not track by the context. It means that EF does not perform any additional task to store the retrieve entities for tracking. We can also change the default behavior of tracking at context instance level.

How do you use AsNoTracking in EF core?

The AsNoTracking() extension method returns a new query and the returned entities will not be cached by the context (DbContext or Object Context). This means that the Entity Framework does not perform any additional processing or storage of the entities that are returned by the query.

Does Entity Framework have tracking?

Entity Framework provides ability to track the changes made to entities and their relations, so the correct updates are made on the database when the SaveChanges method of context is called. This is a key feature of the Entity Framework.


Video Answer


1 Answers

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];
    }
}
like image 141
user2697817 Avatar answered Oct 03 '22 13:10

user2697817