实体框架核心,包括结果中的多级导航属性



在 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 行中使用 ThenInclude Author.Photo 属性。

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

您可以根据需要

(并认为合理)重复相同的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. ...)

最新更新