linq - EF Core 中孙子属性的 Include 与 thenInclude

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

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

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);

最佳答案

它们是等价的。第一个显然是首选,但对于集合导航来说这是不可能的。因此,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));

关于linq - EF Core 中孙子属性的 Include 与 thenInclude,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58394511/

相关文章:

c# - 如何计算 Entity Framework 中的非原始对象列表?

c# - 你用过的最酷的 C# LINQ/Lambdas 技巧?

c# - 如何在 EF 返回给定模型后加载更多数据

c# - SelectMany 应用于 3 个列表

c# - 同时执行两个数据库调用(使用两个 DbContext)

c# - 如何在我的业务逻辑层中管理统一性?

linq - 以不同方式处理第一个 IEnumerable 项目的最优雅方式

c# - 当 IDENTITY_INSERT 设置为 OFF 时,无法在表中插入标识列的显式值

asp.net-core-webapi - 使用 Entity Framework Core 的数据保护

c# - 隔离 EF Core 中的更改