Check if there are any pending changes to be saved

Entity FrameworkEntity Framework-4Entity Framework-5Entity Framework-6

Entity Framework Problem Overview


Is there a way to find out whether there are unsaved changes in my entity context, in the Entity Framework?

Entity Framework Solutions


Solution 1 - Entity Framework

Starting with EF 6, there is context.ChangeTracker.HasChanges().

Solution 2 - Entity Framework

This might work (if by changes you mean added, removed and modified entities):

bool changesMade = (context.ObjectStateManager.GetObjectStateEntries(EntityState.Added).Count() +
                    context.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted).Count() +
                    context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Count()
                    ) > 0;

Edit:

Improved code:

bool changesMade = context.
                   ObjectStateManager.
                   GetObjectStateEntries(EntityState.Added | 
                                         EntityState.Deleted | 
                                         EntityState.Modified
                                        ).Any();

Solution 3 - Entity Framework

For those of you using EF 4+, here is an equivalent solution as an extension method:

public static class DbContextExtensions {
    public static Boolean HasPendingChanges(this DbContext context) {
        return context.ChangeTracker.Entries()
                      .Any(e => e.State == EntityState.Added
                             || e.State == EntityState.Deleted
                             || e.State == EntityState.Modified);
    }
}

Note that you can't combine the values as a bit mask. The function GetObjectStateEntries() handled the logic for you, but LINQ won't produce proper results.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPalantirView Question on Stackoverflow
Solution 1 - Entity FrameworkThaodenView Answer on Stackoverflow
Solution 2 - Entity FrameworkYakimychView Answer on Stackoverflow
Solution 3 - Entity FrameworkYuckView Answer on Stackoverflow