Sfmar
Sfmar

Reputation: 159

Display ICollection in View

I'm developing a project on ASP.NET MVC5 and using EF6. I have the following classes, with a one-to-many relationship between Author and Book, where an Author can have multiple Books and a Book can only belong to one Author:

Models:

public class Author 
{
   public int AuthorId { get; set; }
   public string Name { get; set; }

   public ICollection<Book> Books { get; set; }
}

public class Book 
{
   public int BookId { get; set; }
   public string Name { get; set; }

   public int? AuthorId { get; set; }
   public Author Author { get; set; }
}

I have generated the approppiate controller with views using EF and now, I want to display for each Author the corresponding associated books' names, in Details.cshtml view.

The Controller:

// GET: Authors/Details/5
public async Task<ActionResult> Details(int? id)
{
    if (id == null)
    {
       return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    Author author = await db.Authors.FindAsync(id);

    if (author == null)
    {
       return HttpNotFound();
    }
       return View(author);
}

My Details.cshtml as follows:

@model MyApp.Models.Author

<div>
    <h4>Author Info</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt style="font-size:20px">
            @Html.DisplayNameFor(model => model.Name)
        </dt>

        <dd style="font-size:20px">
            @Html.DisplayFor(model => model.Name)
        </dd>

        <dt style="font-size:20px">
            Associated Books
        </dt>
        @foreach (var item in Model.Books)
        {
            <dd>
                @item.Name
            </dd>
        }

    </dl>
</div>

But this generates the following error:

Object reference not set to an instance of an object. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

I have followed the answer to this similar question (How to display a collection in View of ASP.NET MVC Razor project?) but, obviously, with no success. Can anyone tell me what am I doing wrong?

Upvotes: 1

Views: 1665

Answers (1)

Marcell Toth
Marcell Toth

Reputation: 3678

Your View is perfectly fine.

The problem is that EF does not load related entities by default (for performance reasons), so the Books property on your Author will remain null.

You have to manually tell the context to load the books as well, by using .Include. For example:

Author author = await db.Authors.Include(a => a.Books).SingleOrDefault(a => a.AuthorId == id);

Upvotes: 3

Related Questions