Consider this aggregate root...
class Contact
{
ICollection<ContactAddress> Addresses { get; set; }
ICollection<ContactItem> Items { get; set; }
ICollection<ContactEvent> Events { get; set; }
}
...which I have used like so...
class Person
{
Contact ContactDetails { get; set; }
}
How do I eager load all of the collections with the contact?
I tried this...
Context
.Set<Person>()
.Include(o => o.ContactDetails)
.ThenInclude(o => o.Addresses)
.ThenInclude(????)
. ...
I've also tried this...
Context
.Set<Business>()
.Include(o => o.ContactDetails.Addresses)
.Include(o => o.ContactDetails.Events)
.Include(o => o.ContactDetails.Items)
On a somewhat related note, is it possible to express what should be returned as part of an aggregate root using fluent configuration?
EF Core has a new extension method ThenInclude (). You can drill down thru relationships to include multiple levels of related data using the ThenInclude method.
This is possible for navigation "chains" that are all references, or when they end with a single collection. This feature was introduced in EF Core 5.0. When applying Include to load related data, you can add certain enumerable operations to the included collection navigation, which allows for filtering and sorting of the results.
This feature was introduced in EF Core 5.0. When applying Include to load related data, you can add certain enumerable operations to the included collection navigation, which allows for filtering and sorting of the results. Supported operations are: Where, OrderBy, OrderByDescending, ThenBy, ThenByDescending, Skip, and Take.
You can also load multiple navigations using a single Include method. This is possible for navigation "chains" that are all references, or when they end with a single collection. This feature was introduced in EF Core 5.0.
The ThenInclude
pattern allows you to specify a path from the root to a single leaf, hence in order to specify a path to another leaf, you need to restart the process from the root by using the Include
method and repeat that for each leaf.
For your sample it would be like this:
Context.Set<Person>()
.Include(o => o.ContactDetails).ThenInclude(o => o.Addresses) // ContactDetails.Addresses
.Include(o => o.ContactDetails).ThenInclude(o => o.Items) // ContactDetails.Items
.Include(o => o.ContactDetails).ThenInclude(o => o.Events) // ContactDetails.Events
...
Reference: Loading Related Data - Including multiple levels
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