尝试更新实体框架中的实体时出现多个ObjectStateManager错误

时间:2013-09-15 03:50:38

标签: c# .net entity-framework

这个问题已经出现了几个月,并且证明非常令人沮丧。

我有一个实体...... StorageContract ...继承自Contract;从TPT(每种类型的表)关系创建(我不确定这是否有所不同)。当我尝试通过将更新的合同定义传递给Update方法来更新现有的StorageContract时...

    public StorageContract UpdateStorageContract(StorageContract contract)
    {
        Context.ObjectContext.ApplyCurrentValues("Contracts", contract);
        Context.SaveChanges();
        return contract;
    }

......我收到了错误......

"An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager"

我发现以下帖子......“An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager”......这导致我尝试“附加”合同参数。

    public StorageContract UpdateStorageContract(StorageContract contract)
    {
        Context.ObjectContext.AttachTo("Contracts", contract);
        Context.SaveChanges();
        return contract;
    }

...这导致错误似乎与之前的错误完全相反......

"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"

第一个错误表明该实体无法更新,因为无法找到它......因为这个实体似乎暗示它无法更新,因为它已经存在(??)。无论如何,这导致我发表以下帖子......“An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key”。所以我再次基于那个代码重新编写代码......

    public StorageContract UpdateStorageContract(StorageContract contract)
    {
        var origEntry = Context.Entry<StorageContract>(contract);

        if (origEntry.State == System.Data.EntityState.Detached)
        {
            var set = Context.Set<StorageContract>();
            StorageContract attachedEntity = set.Find(contract.Id);

            if (attachedEntity != null)
            {
                var attachedEntry = Context.Entry(attachedEntity);
                attachedEntry.CurrentValues.SetValues(contract);
            }
            else
            {
                origEntry.State = System.Data.EntityState.Modified;
            }
        }
        Context.SaveChanges();
        return contract;
    }

导致同样的错误...

"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"

我正在追逐一个洞穴,每一个洞都在洞穴里!我非常渴望得到这个帮助!!

谢谢!

1 个答案:

答案 0 :(得分:1)

你介意试试这个:

var set = Context.Set<StorageContract>().Local;
StorageContract attachedEntity = set.Find(contract.Id);

差异在于本地。