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);
}