代码之家  ›  专栏  ›  技术社区  ›  Palantir

Check if there are any pending changes to be saved

  •  64
  • Palantir  · 技术社区  · 14 年前

    是否有方法确定实体框架中的实体上下文中是否存在未保存的更改?

    3 回复  |  直到 10 年前
        1
  •  57
  •   Yakimych    14 年前

    这可能会起作用(如果你的意思是添加、删除和修改的实体):

    bool changesMade = (context.ObjectStateManager.GetObjectStateEntries(EntityState.Added).Count() +
                        context.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted).Count() +
                        context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Count()
                        ) > 0;
    

    编辑:

    改进代码:

    bool changesMade = context.
                       ObjectStateManager.
                       GetObjectStateEntries(EntityState.Added | 
                                             EntityState.Deleted | 
                                             EntityState.Modified
                                            ).Any();
    
        2
  •  76
  •   Thaoden    10 年前

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

        3
  •  42
  •   Yuck    11 年前

    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. 函数 GetObjectStateEntries() handled the logic for you, but LINQ won't produce proper results.