Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I eagerly Include the child and grandchild elements of an entity in Entity Framework Code First?

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

A Customer has many Books

A Book has one Author

I use that data to print a report like this:

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: J. R. R. Tolkien 

When I query for Customers I get, as expected, a bunch of queries of the following nature

  1. A query to get the Customers
  2. A query per Customer to get his Books
  3. A query per Book to get its author

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

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

But I don't know how to load the third level (Author). How can I do that?

like image 363
adolfojp Avatar asked May 06 '11 00:05

adolfojp


People also ask

What is include and ThenInclude in Entity Framework?

Entity Framework Classic ThenIncludeThe ThenInclude method moves the chaining level to the property included. It allows us to include related objects from the next level. ThenInclude is a syntactic sugar method to make it easier and clearer to include multiple related objects.

What are the three approaches in Entity Framework?

There are three approaches to model your entities in Entity Framework: Code First, Model First, and Database First. This article discusses all these three approaches and their pros and cons.

What are the ways we can load the related entities in Entity Framework?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.


2 Answers

Also, it isn't necessary to use the string overload. This method will work too:

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

For more examples see the EF team blog post: 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

like image 191
tdykstra Avatar answered Nov 15 '22 23:11

tdykstra


There's an overload for Include that accepts a string which can denote the full path to any extra properties you need:

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

It looks strange because "Author" isn't a property on a collection of books (rather a property on each individual book) but it works. Give it a whirl.

like image 26
Matt Hamilton Avatar answered Nov 16 '22 00:11

Matt Hamilton