13

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();
3
  • Loop through each of the books and call Load on each of their Sales collections? Commented Feb 24, 2020 at 19:12
  • Ehm, alright. Why are you averse to writing a loop? Commented Feb 24, 2020 at 19:14
  • @RobertHarvey, Thanks for your comment. Is there any way I can do it without looping through "Books". My questions does miss the whole purpose of having explicit loading though. Commented Feb 24, 2020 at 19:16

1 Answer 1

28

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.