ThenInclude for Explicit Loading in Entity Framework core?

.net .net-core c# entity-framework entity-framework-core

Question

I know I can go 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
1
2/24/2020 7:12:55 PM

Accepted Answer

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();
3
2/24/2020 7:31:28 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow