EF Core包含多个子级别集合

时间:2016-10-21 16:54:52

标签: c# entity-framework entity-framework-core

考虑这个聚合根...

class Contact 
{
    ICollection<ContactAddress> Addresses { get; set; }
    ICollection<ContactItem> Items { get; set; }
    ICollection<ContactEvent> Events { get; set; }
}

......我曾经这样使用过......

class Person 
{
    Contact ContactDetails { get; set; }
}

如何通过联系人急切加载所有馆藏?

我试过了......

Context
    .Set<Person>()
    .Include(o => o.ContactDetails)
    .ThenInclude(o => o.Addresses)
    .ThenInclude(????)
    . ...

我也试过这个......

Context
    .Set<Business>()
    .Include(o => o.ContactDetails.Addresses)
    .Include(o => o.ContactDetails.Events)
    .Include(o => o.ContactDetails.Items)

在一个有点相关的说明中,是否可以使用流畅的配置表达应该作为聚合根的一部分返回的内容?

1 个答案:

答案 0 :(得分:12)

ThenInclude模式允许您指定从根到单个叶的路径,因此为了指定另一个叶的路径,您需要从root使用Include方法并为每个叶子重复一次。

对于您的样本,它将是这样的:

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
    ...