Check if there are any pending changes to be saved

2019-01-22 04:56发布

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

3条回答
别忘想泡老子
2楼-- · 2019-01-22 05:44

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

查看更多
Summer. ? 凉城
3楼-- · 2019-01-22 05:46

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();
查看更多
在下西门庆
4楼-- · 2019-01-22 05:49

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.

查看更多
登录 后发表回答