Entity Relations for EF7 MVC6

asp.net-core entity-framework-core

Question

My goal here is to use EF7 with MVC6 [BETA2] to list a number of bookshelves and the number of books on each shelf.

The database schema is created correctly with the correct table relationships. I can successfully add shelves and books to the database including the foreign key relationships (see code below).

When I test the index page that should show the book count on each shelf, I receive no book count data and no errors. In the Shelf entity the property Books remains unpopulated with Book entities thus the count is null (see code below).

In EF7 is there somewhere where I need to write code to populate Shelf.Books or should this happen automatically in EF7?

BookShelf.cs

namespace MyApp.Models
{
    public class Shelf
    {
        public int ShelfId { get; set; }
        public string Name { get; set; }
        public virtual List<Books> Books { get; set; }
    }

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

ApplicationDbContext.cs

namespace MyApp
{
    public class ApplicationDBContext
    {
        public DbSet<Shelf> Shelf { get; set; }
        public DbSet<Book> Book { get; set; }
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Shelf>().Key(s => s.ShelfId);
        builder.Entity<Book>().Key(b => b.BookId);

        builder.Entity<Shelf>()                
            .OneToMany(s => s.Book)
            .ForeignKey(k => k.ShelfId);

        base.OnModelCreating(builder);
    }
}

ShelfController.cs

namespace MyApp
{
    private ApplicationDBContext db;

    public BuildingsController(ApplicationDBContext context)
    {
        db = context;
    }

    // GET: Shelves
    public async Task<IActionResult> Index()
    {
        return View(await db.Shelves.ToListAsync());
    }
}

Index.cshtml

...
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Books.Count)
        </td>
    </tr>
}
....

Popular Answer

What I have discovered is that EF does not populate the parent object with related children objects out of the box. Example, myShelf.Books will be empty until populated in the controller action function.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why