Detect if an entity framework object has changed

c# entity-framework


I want to check if an entity object has changed (including if any of its children have been modified). I'm using Entity Framework 4.4

My code basically loads in the object from the DB and applies values to some properties (however they may be the same as the original).

I know I can check entityObject.EntityState, but does it update if children have a change, or do I need to loop through all the children in the object?

This is because if it has I need to run a whole bunch of other code (like send an email alert to a user and stuff saying that values have been updated, but I don't want to run that code if they haven't been updated).

10/7/2013 1:55:49 PM

Accepted Answer

For EF 5 use DbContext's ChangeTracker:

 public bool HasUnsavedChanges()
    return this.ChangeTracker.Entries().Any(e => e.State == EntityState.Added
                                              || e.State == EntityState.Modified
                                              || e.State == EntityState.Deleted);

For EF 6 use the ChangeTracker.HasChanges() method which will also detect changes in many to many relationships:

 public bool HasUnsavedChanges()
    return this.ChangeTracker.HasChanges();
1/22/2020 8:14:39 AM

Popular Answer

I know as you are using Entity Framework 5, this answer will not help you, but it may help others.

Starting with Entity Framework 6 and in Entity Framework Core you can check for changes simply by following line of code:


Related Questions


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