[英]EntityFramework Core including multilevel navigation properties in results
In EF Core, we can use .Include
and .ThenInclude
methods to load related data in queries.在 EF Core 中,我们可以使用
.Include
和.ThenInclude
方法在查询中加载相关数据。 Let's take the example from the official documentation:我们以官方文档中的例子为例:
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.}
In the example above, it included the Post.Author
property and then the Author.Photo
property using ThenInclude
in lines 5 and 6.在上面的例子,它包括在
Post.Author
属性,然后Author.Photo
使用属性ThenInclude
在线路5和6。
But what if the Post
entity has another navigation property that I want to include?但是如果
Post
实体有另一个我想要包含的导航属性怎么办? If I use ThenInclude
after line 6, it will be relative to the Photo
property and if I use Include
it will be relative back to the Blogs
property.如果我在第 6 行之后使用
ThenInclude
,它将相对于Photo
属性,如果我使用Include
,它将相对于Blogs
属性。 Is there any way to solve this directly in the query statement?有什么办法可以直接在查询语句中解决这个问题吗?
You can repeat identical Include
s as often as you like (and deem sensible):您可以随心所欲地重复相同的
Include
s(并且认为是明智的):
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. ...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.