【问题标题】:EFCore 2.0 - Include & ThenInclude : child collection -- grandchild collection [duplicate]EF Core 2.0 - Include 和 ThenInclude :子集合-孙子集合 [重复]
【发布时间】:2019-01-03 22:53:10
【问题描述】:

对于像下面这样的模型

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

    public List<Child> Children { get; set; }
}

public class Child
{
    public int ChildId { get; set; }

    public int ParentId { get; set; }

    public List<Child> GrandChildren { get; set; }
}

public class GrandChild
{
    public int GrandChildId { get; set; }

    public int ChildId { get; set; }
}

如何编写一个查询来获取 Include/ThenInclude 语句中的所有 Children 和 GrandChildren?

var record = GetAll()
 .Where(r => r.Id == 4)
 .Include(r => r.Children)
     .ThenInclude(????????????)

在“ThenInclude”语句中,我不能使用 select 语句来获取孙子。获得 GrandChildren 收藏的正确方法是什么?

非常感谢。

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    只需键入导航属性名称:

    .ThenInclude(c => c.GrandChildren)
    

    这是 EF Core 文档的 Including multiple levels 部分中特别提到的当前 Intellisense 问题:

    注意

    当前版本的 Visual Studio 提供了不正确的代码完成选项,当在集合导航属性后使用 ThenInclude 方法时,可能会导致正确的表达式被标记为语法错误。这是在 https://github.com/dotnet/roslyn/issues/8237 跟踪的 IntelliSense 错误的症状。只要代码正确并且可以成功编译,忽略这些虚假的语法错误是安全的。

    【讨论】:

    • “GrandChilden”的这个属性没有出现在智能感知中,这让我感到困惑。根据你的建议,包含孙子后,代码编译得很好。
    • 我知道。第一次碰到它时,每个人都会感到困惑。
    • 我用错误 Visual Studio 2019 确认了这一点。您的澄清帮助了我。
    • 请注意,该错误仍然出现在最新(VS 2019 16.4)版本中:follow-up issue。但是,它似乎将在 16.5 中修复。
    • @Carsten 是的,确实如此,尽管 EF Core 人员从他们的文档中删除了上述注释。
    猜你喜欢
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 2011-08-23
    • 1970-01-01
    • 2021-04-21
    相关资源
    最近更新 更多