【发布时间】:2014-05-30 12:10:51
【问题描述】:
我的模型:
public class Inventory
{
public int ID { get; set; }
public float Amount { get; set; }
public ApplicationUser Owner { get; set; }
public Item Item { get; set; }
public Unit Unit { get; set; }
}
public class Unit
{
public int ID { get; set; }
public string Abbreviation { get; set; }
public string FullName { get; set; }
public UnitType Type { get; set; }
}
当将控制器中的所有库存传递给视图时,视图中的 Unit 字段始终为空,无论数据库中有什么。
正在调用的控制器中的操作:
public ActionResult Index()
{
return View(db.Inventorys.ToList());
}
相关视图部分:
@model IEnumerable<App.Models.Inventory>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Amount)
</td>
<td>
@Html.DisplayFor(modelItem => item.Unit.Abbreviation)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
第二个 DisplayFor (item.Unit.Abbreviation) 从不显示任何内容。我在视图上放了一个断点,Model 中的所有模型都没有对其他模型的引用的值。
数据库数据(链接到图片,因为我没有足够的代表):
我正在使用代码优先开发。
【问题讨论】:
-
您当前的 Index 代码仅指向 FK。您必须在代码中显式加载 FK 关系。请使用 faby 给出的答案。
标签: c# ef-code-first asp.net-mvc-5