EF Core 包含在多个子级集合中 [英] EF Core Include on multiple sub-level collections

查看:59
本文介绍了EF Core 包含在多个子级集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个聚合根...

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?

我试过了...

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)

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

推荐答案

ThenInclude 模式允许您指定从根到单个叶子的路径,因此在为了指定到另一个叶子的路径,您需要使用 Include 方法从根重新启动该过程,并对每个叶子重复该过程.

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

参考: 加载相关数据 - 包括多个级别

这篇关于EF Core 包含在多个子级集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆