Check if there are any pending changes to be saved


Question

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

Accepted Answer

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();

Popular Answer

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





Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why