Let’s look at how you would get the List<Book> Books from the Author model. We’ll use Author’s Detail View and then extract that to a Partial View. A common error is to get a null pointer exception here:
1 |
@foreach (var item in Model.Books) |
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
This is fixed by adding Virtual to the Books property. Now, when we go to the Author’s Detail page, the Books property is instantiated and the list can be displayed.
1 2 3 4 5 6 7 8 9 10 11 12 |
using System.Collections.Generic; namespace BookStore.Models { public class Author { public int AuthorId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual List<Book> Books { get; set; } } } |
1 2 3 4 5 6 7 8 9 10 |
namespace BookStore.Models { public class Book { public int BookId { get; set; } public int AuthorId { get; set; } public Author Author { get; set; } public string Title { get; set; } } } |
1 2 3 4 5 |
PM> Add-Migration Virtual Scaffolding migration 'Virtual'. PM> Update-Database Applying explicit migration: 201811301319400_Virtual. Running Seed method. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
@model BookStore.Models.Author @{ ViewBag.Title = "Details"; } <h2>Details</h2> <div> <h4>Author</h4> <hr /> <dl class="dl-horizontal"> <dt> @Html.DisplayNameFor(model => model.FirstName) </dt> <dd> @Html.DisplayFor(model => model.FirstName) </dd> <dt> @Html.DisplayNameFor(model => model.LastName) </dt> <dd> @Html.DisplayFor(model => model.LastName) </dd> <dt> @foreach (var item in Model.Books) { @Html.DisplayFor(modelItem => item.Title) } </dt> </dl> </div> |