这个问题已经出现了数月之久,事实证明它非常令人沮丧。
我有一个实体 ... 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/