我还在学习ASP.NET MVC的细微差别,这是我遇到的最新绊脚石。我使用生成器项目从现有数据库创建我的“代码优先”模型类。这是我的代码的一些关键部分:
// ***** Parent model
public partial class Network
{
public int Id { get; set; }
public virtual ICollection<NetworkDevice> NetworkDevices { get; set; }
// Other attributes removed for brevity
}
// ***** Child model
public partial class NetworkDevice
{
public int Id { get; set; }
public string Description { get; set; }
// Reference to parent model
public virtual Network Network { get; set; }
// Other attributes removed for brevity
}
// ***** Controller code
NetworkManagementEntities _db = new NetworkManagementEntities();
//
// GET: /Device/Edit/5
public ActionResult Edit(int id)
{
NetworkDevice model = _db.NetworkDevices.FirstOrDefault(n => n.Id == id);
return View(model);
}
//
// POST: /Device/Edit/5
[HttpPost]
public ActionResult Edit(NetworkDevice model)
{
try
{
if (ModelState.IsValid)
{
_db.Entry(model).State = EntityState.Modified;
_db.SaveChanges();
// This is where the exception occurs because model.Network is null
return RedirectToAction("Edit", "Network", new { id = model.Network.Id });
}
return View(model);
}
catch
{
return View(model);
}
}
我的问题是......如何确保可以引用父网络属性,以便我可以在编辑后正确重定向?
(可能会对此问题有所了解的一些其他背景信息:当模型类首次生成时,NetworkDevice上的一个属性是Network_ID,它将外键列与父网络表匹配。但是,我有从模型中删除此属性,因为在网络的编辑视图中,我正在显示子NetworkDevice记录的网格,并且在构建该网格的代码中,当我尝试迭代Model.Network.NetworkDevices时会抛出异常。抛出的异常是“元数据集合中的多个项目与标识'Network_Id'匹配。”)
更新:我提出的解决方案是将Network_ID属性保留在NetworkDevice类中,但使用[ForeignKey]属性进行修饰,这消除了上述异常。然后在更新后构建重定向URL时引用Network_ID。