ChatGPT解决这个技术问题 Extra ChatGPT

在第二级包括几个参考

假设我们有这个模型:

public class Tiers
{
    public List<Contact> Contacts { get; set; }
}

public class Contact
{
    public int Id { get; set; }
    public Tiers Tiers { get; set; }
    public Titre Titre { get; set; }
    public TypeContact TypeContact { get; set; }
    public Langue Langue { get; set; }
    public Fonction Fonction { get; set; }
    public Service Service { get; set; }
    public StatutMail StatutMail { get; set; }
}

使用 EF7,我想用一条指令从 Tiers 表中检索所有数据,从 Contact 表、Titre 表、TypeContact 表等中检索所有数据。使用 Include/ThenInclude API,我可以编写如下内容:

_dbSet
     .Include(tiers => tiers.Contacts)
          .ThenInclude(contact => contact.Titre)
     .ToList();

但是在 Titre 属性之后,我不能包含其他引用,例如 TypeContact、Langue、Fonction ... Include 方法建议使用 Tiers 对象,然后 ThenInclude 建议使用 Titre 对象,而不是 Contact 对象。如何包含我的联系人列表中的所有引用?我们可以通过一条指令实现这一目标吗?


v
vivek nuna

.ThenInclude() 将链接最后一个 .ThenInclude() 或最后一个 .Include()(以较新者为准)以拉入多个级别。要在同一级别包含多个同级,只需使用另一个 .Include() 链。正确格式化代码可以大大提高可读性。

_dbSet
    .Include(tiers => tiers.Contacts).ThenInclude(contact => contact.Titre)
    .Include(tiers => tiers.Contacts).ThenInclude(contact => contact.TypeContact)
    .Include(tiers => tiers.Contacts).ThenInclude(contact => contact.Langue);
    // etc.

顺便说一句,这个问题启发了我创建问题 #2124
为什么不:var contacts = _dbSet.Include(tiers => tiers.Contacts); contacts.ThenInclude(contact => contact.Titre); contacts.ThenInclude(contact => contact.TypeContact); contacts.ThenInclude(contact => contact.Langue); 那不行吗?
@Doug 不,您每次都会创建新的 Queryable 对象并且从不评估它们。 contacts 只会有您分配给它的原始值。
此解决方案有效,但生成的 SQL 语句会导致三个 LEFT JOIN 与联系人(至少根据我的经验)。这是非常低效的。一定有更好的方法。
对于新寻求者:在 2020 年,使用 EF Core 3.1,我对已接受解决方案的测试运行良好,并且没有导致 3 个左连接。
R
Risadinha

为了完整起见:

也可以通过 Include如果它们不是集合属性直接包含嵌套属性,如下所示:

_dbSet
    .Include(tier => tier.Contact.Titre)
    .Include(tier => tier.Contact.TypeContact)
    .Include(tier => tier.Contact.Langue);

关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅