ObjectStateManager.TryGetObjectStateEntry为附加对象返回false

Jer*_*oen 5 entity-framework-4 ef-code-first

TryGetObjectStateEntry返回false,但是当我尝试附加实体时,我得到'具有相同键的对象已存在于ObjectStateManager中.ObjectStateManager无法使用相同的键跟踪多个对象.

实体键的类型为Guid.

这怎么可能?

编辑:我正在附加2个具有不同键的实体.错误始终发生在我附加的此类型的第二个实体上.如果我交换它们,错误仍然在第二个.

    public bool IsAttached<T>(T obj) where T : class
    {
        ObjectStateEntry entry = null;

        ObjectContext objCtx = GetObjectContext();

        bool isKeyAttached = false;

        EntityContainer container = objCtx.MetadataWorkspace.GetEntityContainer(objCtx.DefaultContainerName, DataSpace.CSpace);
        EntitySetBase entitySet = container.BaseEntitySets.Where(item => item.ElementType.Name.Equals(typeof(T).Name)).FirstOrDefault();
        System.Data.EntityKey key = objCtx.CreateEntityKey(entitySet.Name, obj);

        if (objCtx.ObjectStateManager.TryGetObjectStateEntry(key, out entry))
        {
            isKeyAttached = entry.State != System.Data.EntityState.Detached;
        }

        return isKeyAttached;
     }
Run Code Online (Sandbox Code Playgroud)

Sla*_*uma 1

如果您附加的实体具有引用其他实体的导航属性,则可能会出现此问题。例子:

public class Parent
{
    public int Id { get; set; }
    public Child Child { get; set; }
}

public class Child
{
    public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

下面的代码会抛出异常:

using (var context = new MyDbContext())
{
    var parent = new Parent { Id = 1 };
    var child1 = new Child { Id = 1 };
    parent.Child = child1;

    var child2 = new Child { Id = 1 };  // same key

    context.Children.Attach(child2);    // child with key = 1 is attached now

    var objContext = ((IObjectContextAdapter)context).ObjectContext;

    ObjectStateEntry entry;
    bool isAttached = objContext.ObjectStateManager.TryGetObjectStateEntry(
        new EntityKey("MyDbContext.Parents", "Id", parent.Id), out entry);
    // isAttached will be false because a Parent with Id = 1 is not attached
    if (!isAttached)
    {
        // we assume now that we could attach the parent safely
        context.Parents.Attach(parent);

        // Assumption is wrong -> Exception, because Attach attaches the whole
        // object graph, so it tries also to attach child1 together with parent
        // But child1 has the same key as child2 which is already attached
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,重点是TryGetObjectStateEntry仅检查基本实体的状态,而不考虑任何导航属性。Attach另一方面,不仅附加基本实体,还附加尚未附加的子实体,从而导致异常。