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

实体 key 的类型为Guid。

这怎么可能?

编辑:我要附加2个具有不同 key 的实体。该错误总是发生在我附加的这种类型的第二个实体上。如果我交换它们,错误仍然在第二个。

    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;
     }

最佳答案

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

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

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

以下代码将引发异常:
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
    }
}

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

关于entity-framework-4 - ObjectStateManager.TryGetObjectStateEntry对于附加的对象返回false,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7938728/

10-13 09:31