MVC4外键属性为null

时间:2015-10-27 17:28:27

标签: c# entity-framework asp.net-mvc-4 one-to-many

我有一个费用和类别表。我已经在表中添加了少量条目,但是当从DB中提取时,Category属性为null。我希望它会自动填充Category表中的条目。我错过了什么?

型号:

public class Expense
{
    public int ExpenseId { get; set; }

    [DataType(DataType.Currency)]
    public decimal Amount { get; set; }

    [ForeignKey("CategoryId")]
    public Category Category { get; set; }

    [Required(ErrorMessage = "You must select some category!")]
    public int CategoryId { get; set; }
}
public class Category
{
    public int CategoryId { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Expense> Expenses { get; set; }
}

查看:

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Amount)
        </td>
        <td>
            @item.CategoryId
        </td>
        <td>
            @item.Category.Description //NullReferenceException here
        </td>
    </tr>

控制器:

// GET: Expenses
    public ActionResult Index()
    {
        return View(db.Expenses.ToList());
    }

1 个答案:

答案 0 :(得分:1)

尝试将Category属性标记为virtual。如果没有急切加载,导航属性需要是虚拟的以支持延迟加载。