3

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

我有一个实体 ... 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"

我找到了以下帖子...“在 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"

第一个错误表明该实体无法更新,因为它找不到......而这个似乎表明它无法更新,因为它已经存在(??)。无论如何,这让我看到了下面的帖子......“ ObjectStateManager 中已经存在具有相同键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象”。所以我基于此再次修改了代码......

    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"

我正在追赶这个动不动就塌陷的兔子洞!我迫切需要这方面的帮助!!

谢谢!

4

1 回答 1

1

你介意试试这个:

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

区别在于本地。

于 2013-09-15T05:48:03.500 回答