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) Explicit Loading : This type of loading if force loading. This behaviour is like lazy loading but lazy loading disabled (in EF 6), it is still possible to lazily load related entities, but it must be done with an explicit call. We can implement it with use the Load() method to load related entities explicitly.
Disable Lazy Loading To turn off lazy loading for a particular property, do not make it virtual. To turn off lazy loading for all entities in the context, set its configuration property to false.
EF Core will then enable lazy loading for any navigation property that can be overridden--that is, it must be virtual and on a class that can be inherited from. For example, in the following entities, the Post. Blog and Blog. Posts navigation properties will be lazy-loaded.
You can explicitly load a navigation property via the DbContext. Entry(...) API. You can also explicitly load a navigation property by executing a separate query that returns the related entities.
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();
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