c# - 尝试更新 Entity Framework 中的实体时出现多个 ObjectStateManager 错误

标签 c# .net entity-framework

这个问题已经出现了数月之久,事实证明它非常令人沮丧。

我有一个实体 ... StorageContract ... 它继承自 Contract;从 TPT(每个类型的表)关系创建(我不确定这是否有所作为)。当我尝试通过将契约(Contract)的更新定义传递给 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"

我正在追逐一个随时都会塌陷的兔子洞!我迫切需要这方面的帮助!!

谢谢!

最佳答案

你介意试试这个吗:

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

区别在于本地。

关于c# - 尝试更新 Entity Framework 中的实体时出现多个 ObjectStateManager 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18808753/

相关文章:

c# - 我应该使用 ORM 来为大型树结构建模吗?

c# - 导航属性的唯一约束

c# - SP 在 EF 5 CF 中有多个结果

c# - .NET 中的字符串编码不可知吗?

c# - Unity DI,多个命名实例

c# - 如何用私钥加密字符串并用公钥解密?

c# - ADO.NET 实体数据模型 BUG

c# - x 深度的所有文件夹和文件的列表

c# - 制作只读本地字符串 C#

.net - 时区、CDO、美国东部标准时间