22

I want to be able to tell if there is any unsaved data in an entity framework context. I have figured out how to use the ObjectStateManager to check the states of existing entities, but there are two issues I have with this.

  1. I would prefer a single function to call to see if any entities are unsaved instead of looping though all entities in the context.
  2. I can't figure out how to detect entities I have added. This suggests to me that I do not fully understand how the entity context works. For example, if I have the ObjectSet myContext.Employees, and I add a new employee to this set (with .AddObject), I do not see the new entity when I look at the ObjectSet and I also don't see the .Count increase. However, when I do a context.SaveChanges(), my new entity is persisted...huh?

I have been unable to find an answer to this in my msdn searches, so I was hoping someone here would be able to clue me in.

Thanks in advance.

4

4 回答 4

15
var addedStateEntries = Context
    .ObjectStateManager
    .GetObjectStateEntries(EntityState.Added);
于 2010-04-26T17:14:56.273 回答
9

通过扩展方法(对于每个 ObjectContext):

internal static class ObjectContextExtensions
{
    public static bool IsContextDirty(this ObjectContext objectContext)
    {
        return objectContext
            .ObjectStateManager
            .GetObjectStateEntries(
                EntityState.Added | 
                EntityState.Deleted | 
                EntityState.Modified).Any();
    }
}

或通过部分方法(仅适用于您的 ObjectContext):

partial class MyModel
{
    public bool IsContextDirty()
    {
        return ObjectStateManager
            .GetObjectStateEntries(
                EntityState.Added | 
                EntityState.Deleted |
                EntityState.Modified).Any();
    }
}
于 2012-07-05T14:16:22.520 回答
6

一种获得可重用的单一方法/属性的简单方法,您可以通过创建部分类并添加如下属性来向 ObjectContext 添加新方法:

public partial class MyEntityContext
{
  public bool IsContextDirty
  {
    get
    {
      var items = ObjectStateManager.GetObjectStateEntries(EntityState.Added);
      if(items.Any())
        return true;
      items = ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);
      if (items.Any())
        return true;
      items = ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
      if(items.Any())
        return true;
      return false;
    }
  }
}

根据您要查找的内容,您可以公开其他属性以了解是否只是删除或修改。这种方法可以简化,但我希望清楚你需要做什么。

于 2010-04-26T17:33:05.230 回答
3

本文准确描述了在实体框架中执行变更跟踪所需的内容:

身份解析、状态管理和更改跟踪(实体框架) - MSDN

于 2010-04-26T16:01:36.230 回答