views:

63

answers:

1

Hello!

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

Thanks!

+3  A: 

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();
Yakimych
+1 for being generally on the right track, but use `Any()`, not `Count() > 0`.
Craig Stuntz
Darn it - just read your blogpost regarding this today! Thanks ;)
Yakimych