How do I look to include child and grandson elements in the Entity Framework Code First?

Imagine three entities (Customer, Book, Author) related to this:

Customer has many books

There is one author in the book

I use this data to print a report as follows:

Customer: Peter Book: To Kill a Mockingbird - Author: Harper Lee Book: A Tale of Two Cities - Author: Charles Dickens Customer: Melanie Book: The Hobbit - Author: JRR Tolkien 

When I request for Clients, I receive, as expected, a bunch of requests of the following nature

  • Customer Request
  • Request for a client to receive his books
  • Request for a book to get its author

I can reduce the number of queries by including books like this:

var customers = db.Customers.Include (c => c.Books);

But I do not know how to download the third level (Author). How can i do this?

+56
entity-framework ef-code-first eager-loading
May 6 '11 at
source share
3 answers

There is an overload for Include that takes a string that can indicate the full path to any additional properties that you need:

 var customers = db.Customers.Include("Books.Author"); 

This looks strange because the "Author" is not a property in a collection of books (rather, a property in each individual book), but it works. Give him a whirlwind.

+45
May 6 '11 at 12:53 a.m.
source share

In addition, there is no need to use line overloading. This method will also work:

 var customers = db.Customers.Include(c => c.Books.Select(b => b.Author)); 

For more examples, see the EF blog blog: http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related -entities.aspx

And this tutorial: http://www.asp.net/entity-framework/tutorials/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application

+136
May 6 '11 at 21:59
source share

You can use the ThenInclude keyword:

var customers = db.Customers.Include(c => c.Books).ThenInclude(book => book.Author));}

0
Jan 31 '19 at 13:17
source share



All Articles