【问题标题】:Include vs. ThenInclude for grandchild properties in EF CoreEF Core 中孙子属性的 Include 与 ThenInclude
【发布时间】:2020-02-12 03:00:14
【问题描述】:

这些方法之一是加载孙子属性的首选方法吗?我喜欢第一个的简洁,但我不知道它是否更昂贵。

return source
    .Include(x => x.Server)
    .Include(x => x.Server.User)
    .Include(x => x.Server.ParentServer)
    .Include(x => x.Server.DataCenter);

或

return source
    .Include(x => x.Server)
        .ThenInclude(s => s.User)
    .Include(x => x.Server)
        .ThenInclude(s => s.ParentServer)
    .Include(x => x.Server)
        .ThenInclude(s => s.DataCenter);

【问题讨论】:

    标签: linq entity-framework-core ef-core-2.2


    【解决方案1】:

    它们是等价的。第一个显然是首选,但对于集合导航是不可能的。因此,ThenInclude()。

    // Won't compile
    return source
        .Include(x => x.Posts.Authors)
        .Include(x => x.Posts.Comments);
    
    // Compiles
    return source
        .Include(x => x.Posts)
            .ThenInclude(x => x.Authors)
        .Include(x => x.Posts)
            .ThenInclude(x => x.Comments);
    

    但是,如果你想放弃编译时类型安全,你也可以只使用字符串重载。

    // Compiles, may throw
    return source
        .Include("Posts.Authors")
        .Include("Posts.Comments");
    

    但是请不要这样做......

    // Over-thinking it ;-)
    return source
        .Include(nameof(Blog.Posts) + "." + nameof(Post.Authors))
        .Include(nameof(Blog.Posts) + "." + nameof(Post.Comments));
    

    【讨论】:

    • 顺便说一句,EF6 支持这个:source.Include(x => x.Posts.Select(y => y.Comments))(但我们不喜欢它)
    【解决方案2】:

    这是一个非常有趣的问题!如果 EF (Core) 文档,则根本没有记录这一点。

    几周前我对此进行了一些测试,我的结论是这些方法之间没有区别。

    我尝试了几十种场景,从最简单和最愚蠢的场景到 8 级关系层次结构,生成的 SQL 请求始终100% 相同。

    然后我查看了 EF Core 的源代码,发现 Include() 和 ThenInclude() 实现之间没有真正的区别。

    所以我的回答不是 100% 肯定,也许我遗漏了什么,但是,我认为这两种方法是相同的。

    如果您想要一个明确的答案,我认为最好的方法是在EF Core's repo 上提问。

    【讨论】:

    • 无需提交问题。我们一直在看……?
    • 太好了,感谢您的澄清,我忘记了集合导航的细微差别
    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多