How to call ThenInclude twice in EF Core?
Now, this works fine, but as you can see I'm calling .Include(u = u.Posts) twice. Is there a way to call ThenInclude twice on same property, without actually writing the Include statement also twice?
Calling Include(u => u.Posts)
twice is the right way to do it.
From EF Core docs... emphasis on the last sentence.
You may want to include multiple related entities for one of the entities that is being included. For example, when querying
Blog
s, you includePosts
and then want to include both theAuthor
andTags
of thePosts
. To do this, you need to specify each include path starting at the root. For example,Blog -> Posts -> Author
andBlog -> Posts -> Tags
. This does not mean you will get redundant joins, in most cases EF will consolidate the joins when generating SQL.
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.Include(blog => blog.Posts)
.ThenInclude(post => post.Tags)
.ToList();
}
You cannot use ThenInclude
with multiple navigation properties. You have to have Include
.
Here is bug opened for this.