【问题标题】:Including multiple children of child table包括子表的多个子项
【发布时间】:2021-09-27 13:23:54
【问题描述】:

我有以下使用实体框架的数据库查询。

var results = await DbContext.TransloadingDetails
                    .Include(td => td.PurchaseOrder).ThenInclude(po => po.Customer)
                    .Include(td => td.PurchaseOrder).ThenInclude(po => po.Location);

我只是好奇两次这样包含PurchaseOrder 的后果。如果不包含两次,我认为无法表达这一点。是否可以安全地忽略重复项?

【问题讨论】:

  • 是的,EF 会按照你想要的方式解释它。该语法需要包含多个不同的孩子Similar Question
  • 没有任何后果,EF 全力以赴。这就是您可以利用 Linq 方法来包含多个孩子的方法,而无需求助于 .Include(td=> td.PurchaseOrder).Include("PurchaseOrder.Customer").Include("PurchaseOrder.Location") 之类的魔术字符串
  • 可以参考link

标签: c# entity-framework asp.net-core entity-framework-core


【解决方案1】:

这是来自EF Core docs

您可能希望为要包含的实体之一包含多个相关实体。例如,查询Blogs 时,您包含Posts,然后想同时包含PostsAuthorTags。要包含两者,您需要指定从根开始的每个包含路径。例如,Blog -> Posts -> AuthorBlog -> Posts -> Tags。这并不意味着你会得到多余的连接;大多数情况下,EF 会在生成 SQL 时合并连接。

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
        .Include(blog => blog.Posts)
        .ThenInclude(post => post.Tags)
        .ToList();
}

您还可以使用单个 Include 方法加载多个导航。这对于所有引用的导航“链”是可能的,或者当它们以单个集合结尾时。

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Owner.AuthoredPosts)
        .ThenInclude(post => post.Blog.Owner.Photo)
        .ToList();
}

【讨论】:

    猜你喜欢
    • 2021-03-18
    • 2012-05-06
    • 1970-01-01
    • 2021-04-13
    • 2013-02-24
    • 2015-04-02
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    相关资源
    最近更新 更多