How to include a table multiple times in Linq query

Viewed 674

Here is my query, using EntityFramework 6.0

                 var x = context.Student
                .Include(d => d.Class.Select(di => di.Teachers).Select(i => i.Subjects))
                .Include(d => d.Class.Select(di => di.Teachers).Select(di => di.Marks))
                .firstOrDefault();
                

Entities Subject and Class are childern of Teachers entity. How to include both the child entities in one query? When the query is executed, does the Teachers entity will be loaded twice? As the 'class' table is included twice, when the SQL is generated does it joins the 'class' table 2 times?

1 Answers

Are you using EF6 or EF Core? On EF Core you can use ThenInclude to load deeper level entities. Like (from MS Docs):

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
        .ThenInclude(author => author.Photo)
        .Include(blog => blog.Owner)
        .ThenInclude(owner => owner.Photo)
        .ToList();
}
Related