EntityFramework Core包括结果

时间:2017-01-10 21:05:10

标签: entity-framework-core

在EF Core中,我们可以使用.Include.ThenInclude方法在查询中加载相关数据。让我们以官方文档为例:

1. using (var context = new BloggingContext())
2. {
3.     var blogs = context.Blogs
4.         .Include(blog => blog.Posts)
5.            .ThenInclude(post => post.Author)
6.            .ThenInclude(author => author.Photo)
7.         .Include(blog => blog.Owner)
8.            .ThenInclude(owner => owner.Photo)
9.         .ToList();
10.}

在上面的示例中,它包含Post.Author属性,然后在第5行和第6行中使用Author.Photo包含ThenInclude属性。

但是,如果Post实体具有我想要包含的另一个导航属性,该怎么办?如果我在第6行之后使用ThenInclude,它将相对于Photo属性,如果我使用Include,它将相对回Blogs属性。有没有办法直接在查询语句中解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以随意重复相同的Include(并且认为合情合理):

 var blogs = context.Blogs
     .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
        .ThenInclude(author => author.Photo)
     .Include(blog => blog.Posts)
        .ThenInclude(post => post.Document)
     .Include(blog => blog.Posts)
        .ThenInclude(post => post. ...)