实体框架核心渴望加载然后包括在集合 [英] Entity Framework Core Eager Loading Then Include on a collection

查看:102
本文介绍了实体框架核心渴望加载然后包括在集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在执行查询时,我有三个要包含的模型。

I have three Models that I want to include when performing a query.

这是场景。

public class Sale
{
     public int Id { get; set; }
     public List<SaleNote> SaleNotes { get; set; }
}

public class SaleNote
{
    public int Id { get; set; }
    public User User { get; set; }
}

public class User 
{
    public int Id { get; set; }
}

我可以加载SaleNotes这样...

I can eager load the SaleNotes like this...

_dbContext.Sale.Include(s => s.SaleNotes);

然而,尝试使用ThenInclude从SaleNote加载用户模型是具有挑战性的,因为它是一个集合。我找不到任何关于如何渴望加载这种情况的例子。有人可以在下面的代码中提供代码ThenInclude来为集合中的每个项目加载用户。

However, trying to eager load the User model from the SaleNote using ThenInclude is challenging because it is a collection. I cannot find any examples on how to eager load this scenario. Can someone supply the code the goes in the following ThenInclude to load the User for each item in the collection.

_dbContext.Sale.Include(s => s.SaleNotes).ThenInclude(...);


推荐答案

无关紧要 SaleNotes 是集合导航属性。它对于引用和集合应该是一样的:

It doesn't matter that SaleNotes is collection navigation property. It should work the same for references and collections:

_dbContext.Sale.Include(s => s.SaleNotes).ThenInclude(sn=>sn.User);

但是我知道,EF7还支持使用选择扩展方法的旧的多级包含语法:

But as far I know, EF7 also supports the old multi-level Include syntax using Select extension method:

_dbContext.Sale.Include(s => s.SaleNotes.Select(sn=>sn.User));

这篇关于实体框架核心渴望加载然后包括在集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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