你肯定知道为什么会出现以下错误
ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同属性的多个对象 关键。
我想要更新或删除它的我的实体
var p = new Person() // for delete
{
Id = 3,
Name = "A",
Family = "A",
Age = 10
};
var p2 = new Person() // for update
{
Id = 3,
Name = "W",
Family = "W",
Age = 90
};
我的目标是使用下面的代码,但是当使用上面的错误时发生
var attachedEntity = leitner.Set<Person>().Attach(p); // maybe not needed !!! according to @oerkelens comment
leitner.Entry(attachedEntity).State = EntityState.Deleted; // for delete
leitner.Entry(attachedEntity).State = EntityState.Modified; // for update
leitner.SaveChanges();
所以我必须更改它,例如下面的代码
var attachedEntity = leitner.Set<Person>().Local.SingleOrDefault(x => x.Id == 3);
attachedEntity.Name = "W"; // for update
attachedEntity.Family = "W";// for update
attachedEntity.Age = 90;// for update
leitner.Entry(attachedEntity).State = EntityState.Deleted;// for delete
leitner.Entry(attachedEntity).State = EntityState.Modified;// for update
leitner.SaveChanges();
新代码可以工作,但对我来说有两个问题
第一:我必须手动查找ID
SingleOrDefault(x => x.Id == 3) // for update or delete
第二:我必须一一设置属性值
attachedEntity.Name = "W"; // for update
attachedEntity.Family = "W";// for update
attachedEntity.Age = 90;// for update
我无法将我的实体分配给attachedEntity
attachedEntity = p; // does not work same error as above occures
attachedEntity = p2; // does not work same error as above occures
请引导我实现我的目标
我的目标是这样的:
var attachedEntity = leitner.Set<Person>().Attach(p); // may be not needed !!!
leitner.Entry(attachedEntity).State = EntityState.Deleted; // if only use this line above error occures again
leitner.Entry(attachedEntity).State = EntityState.Modified; // if only use this line above error occures again
leitner.SaveChanges();
一次性设置整个“p”(实体),无需一一设置
您已经获得了查找实体的代码,但您应该注意,
.Local
仅在实体先前已从数据库中获取或附加到当前会话中的其他位置时才起作用。
var attachedEntity = leitner.Set<Person>().SingleOrDefault(x => x.Id == 3);
Remove
有
DbSet
方法
leitner.Set<Person>().Remove(attachedEntity);
以及从
SetValues
返回的
DbEntityEntry<Person>
上的
leitner.Entry(attachedEntity)
方法
var p2 = new Person() // for update
{
Id = 3,
Name = "W",
Family = "W",
Age = 90
};
leitner.Entry(attachedEntity).Currentvalues.SetValues(p2);
就我而言,当我想检查数据库中要更新的对象是否具有唯一字段(除 P.K 之外)时,会发生此错误消息,如下所示: ctx.Customers.Select(x => x.CustomerCode == Code).SingleOrDefault(); 之后,以下代码引发了“具有相同键的对象...”错误: ctx.Entry(obj).State = System.Data.Entity.EntityState.Modified; ... ctx.SaveChanges(); 改变 ctx.Customers.Select(x => x.CustomerCode == Code).SingleOrDefault(); 到 ctx.Customers.AsNoTracking().SingleOrDefault(x => x.CustomerCode == Code); 解决了问题!