简体   繁体   中英

EntityFramework Core including multilevel navigation properties in results

In EF Core, we can use .Include and .ThenInclude methods to load related data in queries. 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.

But what if the Post entity has another navigation property that I want to include? 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. 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):

 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. ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM