Jack_of_no_trades
Jack_of_no_trades

Reputation: 362

MVC4 Foreign Key property is null

I have an Expenses and Categories tables. I have seeded the tables with few entries, but when pulled from DB the Category property is null. I would expect it to be automatically populated with entries from Category table. What am I missing?

Model:

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; }
}

View:

@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>

Controller:

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

Upvotes: 0

Views: 82

Answers (1)

Paul
Paul

Reputation: 3815

Try marking the Category property as virtual. Navigation properties need to be virtual to support the lazy loading if it is not eager loaded.

Upvotes: 1

Related Questions