How do I create a Linq query that will return multiple complex properties in a sub property of a table?

24 views Asked by At

With the following classes I would like to create a Linq query for EF core that returns the object Course and the Modules in the Course and then also the Notes and Chapters

This brings back the course the modules in the course and the chapters in the modules and then the notes in the chapters (if there were any). What I want to do is bring the notes and the chapters in modules. What would be the Linq Query syntax for this query?

var course = context.Courses
    .Include(c => c.Modules)
        .ThenInclude(m => m.Chapters)
            .ThenInclude(c => c.Notes)
    .Single(c => c.Id == courseId);
public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Module> Modules { get; set; }
    public Lab Lab { get; set; }
}

public class Module
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Chapter> Chapters { get; set; }
    public List<Note> Notes {get;set;}
}

public class Chapter
{
    public int Id { get; set; }
    public string Title { get; set; }
}
public class Note
{
    public int Id { get; set; }
    public string Content { get; set; }
}
1

There are 1 answers

1
John S On BEST ANSWER

The solution is

var course = context.Courses
.Include(c => c.Modules)
    .ThenInclude(m => m.Chapters)
.Include(c => c.Modules)
    .ThenInclude(c => c.Notes)
.Single(c => c.Id == courseId);