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(...);
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.
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.
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.
Entity Framework Core provides support for Eager Loading using the Include() extension method.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With