【问题标题】:MVC 5 Model properties null but database contains valueMVC 5 模型属性为空,但数据库包含值
【发布时间】: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 中的所有模型都没有对其他模型的引用的值。

数据库数据(链接到图片,因为我没有足够的代表):

Inventory

Units

我正在使用代码优先开发。

【问题讨论】:

  • 您当前的 Index 代码仅指向 FK。您必须在代码中显式加载 FK 关系。请使用 faby 给出的答案。

标签: c# ef-code-first asp.net-mvc-5


【解决方案1】:

我认为问题在于您没有检索 Unit 记录。 如果你的数据库架构的外键设置正确,你可以试试这个

public ActionResult Index()
{
    return View(db.Inventorys.Include(b => b.Unit_ID).ToList() );
}

参考this

【讨论】:

  • public virtual Unit Unit { ... } 也应该这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多