gpt4 book ai didi

c# - {"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."}

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:20 26 4
gpt4 key购买 nike

我有这段代码,但是我得到了异常

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

在其他部分。

 public int AddOrUpdateEntity<T>(T entity) where T : class , IEntity
{
int numberOfobjectsWritten = 0;

using (DalContext dbContext = new DalContext())
{
//If Id == 0 it means it's a new entity in Db and needs to be added
dbContext.Entry<T>(entity).State = entity.Id == 0 ?
EntityState.Added :
EntityState.Modified;

numberOfobjectsWritten = dbContext.SaveChanges();
}
}

最佳答案

这个异常意味着上下文已经跟踪了一个具有相同键的重复实体。每个实体只能被上下文跟踪一次。如果您尝试附加同一实体的另一个实例(它与已跟踪的实例具有相同的 key ),您将收到此异常。

这意味着您尝试更新的实体的另一个实例已被上下文跟踪。因为附加或添加总是应用于整个对象图(它也应用于通过导航属性访问的相关实体),所以有问题的实体不一定是您要修改的实体,而是它的任何关系。

你可以尝试使用dbContext.ChangeTracker.Entries<T>().FirstOrDefault(e => e.Id == entity.Id)检查是否已跟踪具有相同键的实体实例。

关于c# - {"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16505975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com