EF LINQ include multiple and nested entities
In Entity Framework Core (EF.core
) you can use .ThenInclude
for including next levels.
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.ToList();
More information: https://docs.microsoft.com/en-us/ef/core/querying/related-data
Note:
Say you need multiple ThenInclude()
on blog.Posts
, just repeat the Include(blog => blog.Posts)
and do another ThenInclude(post => post.Other)
.
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.Include(blog => blog.Posts)
.ThenInclude(post => post.Other)
.ToList();
Include
is a part of fluent interface, so you can write multiple Include
statements each following other
db.Courses.Include(i => i.Modules.Select(s => s.Chapters))
.Include(i => i.Lab)
.Single(x => x.Id == id);
Have you tried just adding another Include
:
Course course = db.Courses
.Include(i => i.Modules.Select(s => s.Chapters))
.Include(i => i.Lab)
.Single(x => x.Id == id);
Your solution fails because Include
doesn't take a boolean operator
Include(i => i.Modules.Select(s => s.Chapters) && i.Lab)
^^^ ^ ^
list bool operator other list
Update To learn more, download LinqPad and look through the samples. I think it is the quickest way to get familiar with Linq and Lambda.
As a start - the difference between Select
and Include
is that that with a Select you decide what you want to return (aka projection). The Include is a Eager Loading function, that tells Entity Framework that you want it to include data from other tables.
The Include syntax can also be in string. Like this:
db.Courses
.Include("Module.Chapter")
.Include("Lab")
.Single(x => x.Id == id);
But the samples in LinqPad explains this better.