ThenInclude for Explicit Loading in Entity Framework core?

Viewed 1248

I know I can go one step deeper to load related data using ThenInclude in Eager Loading like below example

//Eager Loading
var publisher = await _context.Publishers
                              .Include(pub => pub.Books)
                                  .ThenInclude(book => book.Sales)
                              .Include(pub => pub.Users)
                              .Where(pub => pub.PubId == id)
                              .FirstOrDefaultAsync();

How can I write the same query in Explicit Loading? How do I load data for Sales without looping through books in below case?

//Explicit Loading
var publisher = await _context.Publishers
                              .SingleAsync(pub => pub.PubId == id);

_context.Entry(publisher)
        .Collection(pub => pub.Books)
        .Load();
                 
_context.Entry(publisher)
        .Collection(pub => pub.Users)                
        .Load();
1 Answers

Query() method is your friend.

It's partially explained in the Querying related entities subsection of Explicit loading documentation:

You can also get a LINQ query that represents the contents of a navigation property.

This allows you to do things such as running an aggregate operator over the related entities without loading them into memory.

Example...

You can also filter which related entities are loaded into memory.

Example...

What they forgot to mention is that you can use it also for Include / ThenInclude related data of the explicitly loading data.

e.g.

_context.Entry(publisher)
    .Collection(pub => pub.Books)
    .Query() // <--
    .Include(book => book.Sales) // <--
    .Load();
Related