我有以下 EF 数据语句:
class Model1{
public Int32 Id{ get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public virtual Model3 PropModel31{ get; set; }
public virtual Model3 PropModel32{ get; set; }
}
class Model3{
public Int32 Id{ get; set; }
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
我在不同的地方请求我的实体:
//db being the datacontext
//Partial view of Model1
var model1s = from model1 in db.Model1
select new {
model1.Id,
model1.Prop1,
model1.Prop2,
model1.PropModel31,
model1.PropModel32,
};
后来,我尝试更新模型实体,
public ActionResult Save(Model1 model1)
{
db.Model1.Attach(model1);
var entry = db.Entry(model1);
entry.Property(e => e.Prop1).IsModified = true;
entry.Property(e => e.Prop2).IsModified = true;
...
db.SaveChanges();
}
但我得到以下异常:
ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同键的多个对象。
如果我评论 db.Model1.Attach(model1); 那么我会得到相反的异常:/
无法为属性“Prop1”调用成员“IsModified”,因为上下文中不存在“Model1”类型的实体。要将实体添加到上下文,请调用 DbSet 的 Add 或 Attach 方法
所以,我的猜测是 Model3 实体属性附加到上下文,但如何检查并修复它?
感谢您的帮助。
最佳答案
嗯,由于子实体属性之一 PropModel31 已重置为新属性(Id=0),因此触发了异常。
异常并不是很明确。
感谢 Andrew Counts 投入的时间和专业知识!
关于c# - 实体对象附加/未附加到 dbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324004/