简体   繁体   中英

EF Core Include on multiple sub-level collections

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM