如何使用强类型控制器与EntityObjects?
我的失败经历...
首先,我尝试了以下方法:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, Department Model)
{
db.SaveChanges();
return RedirectToAction("Index");
}
这并没有实际保存任何更改到数据库中。所以,我试图将模型附加到我的ObjectContext:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, Department Model)
{
db.Attach(Model);
db.SaveChanges();
return RedirectToAction("Index");
}
操作失败,因为"带有空EntityKey值的对象无法附加到对象上下文。" 所以我试图分配EntityKey:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, Department Model)
{
Model.EntityKey = (from Department d in db.Department
where d.Id == id
select d).FirstOrDefault().EntityKey;
db.Attach(Model);
db.SaveChanges();
return RedirectToAction("Index");
}
这个操作失败了,因为“一个具有相同键的对象已经存在于ObjectStateManager中。 ObjectStateManager无法跟踪具有相同键的多个对象。”这是怎么回事呢?