我有一个Expenses and Categories表。我用少量条目播种了这些表格,但是当从数据库中取出时,Category属性为null。我希望它会自动填入分类表中的条目。我错过了什么?MVC4外键属性为空
型号:
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());
}
为什么你没有虚拟财产的费用类别? – code