Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core Eager Loading Then Include on a collection

I have three Models that I want to include when performing a query.

Here is the scenario.

public class Sale {      public int Id { get; set; }      public List<SaleNote> SaleNotes { get; set; } }  public class SaleNote {     public int Id { get; set; }     public User User { get; set; } }  public class User  {     public int Id { get; set; } } 

I can eager load the SaleNotes like this...

_dbContext.Sale.Include(s => s.SaleNotes); 

However, trying to eager load the User model from the SaleNote using ThenInclude is challenging because it is a collection. I cannot find any examples on how to eager load this scenario. Can someone supply the code the goes in the following ThenInclude to load the User for each item in the collection.

_dbContext.Sale.Include(s => s.SaleNotes).ThenInclude(...); 
like image 701
Allen Rufolo Avatar asked Jun 27 '16 00:06

Allen Rufolo


People also ask

How do you use include and then include?

The difference is that Include will reference the table you are originally querying on regardless of where it is placed in the chain, while ThenInclude will reference the last table included. This means that you would not be able to include anything from your second table if you only used Include.

How do I set eager loading in Entity Framework?

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method. For example, the queries below will load blogs and all the posts related to each blog. Include is an extension method in the System.

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.

Which of the following is used for the eager loading with Entity Framework?

Entity Framework Core provides support for Eager Loading using the Include() extension method.


1 Answers

It doesn't matter that SaleNotes is collection navigation property. It should work the same for references and collections:

_dbContext.Sale.Include(s => s.SaleNotes).ThenInclude(sn=>sn.User); 

But as far I know, EF7 also supports the old multi-level Include syntax using Select extension method:

_dbContext.Sale.Include(s => s.SaleNotes.Select(sn=>sn.User)); 
like image 118
octavioccl Avatar answered Oct 10 '22 14:10

octavioccl