Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if there are any pending changes to be saved

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

like image 445
Palantir Avatar asked Jun 28 '10 09:06

Palantir


2 Answers

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

like image 126
Thaoden Avatar answered Sep 30 '22 07:09

Thaoden


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(); 
like image 41
Yakimych Avatar answered Sep 30 '22 06:09

Yakimych