0
我有在ASP.NET MVC 3複合主鍵的自參考模型中使用的代碼第一種方法:更新複合外鍵
public class Area
{
[Key, Column(Order=0)]
public int Id1 { get; set; }
[Key, Column(Order=1)]
public int Id2 { get; set; }
public string Name { get; set; }
public virtual Area Parent { get; set; }
}
我想有創建和編輯操作的控制器,可以與所有屬性一起工作,包括複合Parent
(必須預先添加到數據庫中)。
我設法讓create方法運行,但編輯複雜的字段不想更新。以下方法的輸入數據成功解析到對象area
,該對象也具有area.Parent.Id1
和area.Parent.Id2
集。
當前的代碼不進行修改的更改保存到Parent
:
[HttpPost]
public ActionResult Edit(Area area)
{
try
{
if (ModelState.IsValid)
{
if (area.Parent != null)
{
area.Parent = db.Areas.Find(area.Parent.Id1, area.Parent.Id2);
if (area.Parent == null)
throw new NotFoundException();
// need to mark it as modified...
}
db.Entry(area).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (NotFoundException)
{
//...
}
return View(area);
}