Check for any modifications that need to be saved.

entity-framework entity-framework-4 entity-framework-5 entity-framework-6

Question

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

1
71
2/18/2014 3:13:11 PM

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();
58
6/30/2010 7:48:26 PM

Popular Answer

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



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