在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
属性。有没有办法直接在查询语句中解决这个问题?
答案 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. ...)