【发布时间】:2016-04-15 04:20:17
【问题描述】:
尝试使用 MVC 6 和 EF 代码优先设计显示嵌套列表。我正在使用这个Tutorial 让我开始使用 MVC,并试图将它提升到另一个层次。
类:
public class Location
{
[Key]
public int ID { get; set; }
public string LocationName { get; set; }
public ICollection<SubLocation> Sublocations { get; set; }
}
}
public class SubLocation
{
public int ID { get; set; }
public string SubLocationName { get; set; }
}
运行dnx ef database update 正确设置了我的EF 数据库,并在SubLocation 下为LocationID 分配了一个外键。
现在我想在每个位置下显示子位置,如下图所示。用户可以添加与位置相关的新位置或子位置。
显示位置列表很简单:return View(_context.Location.ToList());
要显示子位置的嵌套列表,我应该在控制器还是视图中完成这项工作?
我希望我可以使用如下视图,但 item.Sublocations 是 null,原因我不确定,因为数据库中有数据。:
@foreach (var item in Model) {
<tr>
<td>@Html.DisplayFor(modelItem => item.LocationName)</td>
</tr>
@foreach (SubLocation itm in item.Sublocations)
{
<tr>
<td>@itm.SubLocationName</td>
</tr>
}
}
我尝试在控制器中创建查询,但外键无法用于比较。
var test = (from m in _context.SubLocation
where m.LocationID == curLocID <-- m.LocationID isn't available
select m.SubLocationName
).ToList();
即使我可以使用 LocationID,我也不确定如何将当前位置 (curLocID) 从视图发送回控制器。我想我需要一个辅助方法,但我开始绕圈子了。
如何维护正确的 MVC 并从我的主类的子类显示嵌套列表?
【问题讨论】:
标签: asp.net-mvc entity-framework