I'm trying to efficiently manipulate complex records with multiple levels of nested fields in C# / ASP.NET Core / Entity Framework Core.
I created a small test app with EF models "Departments > Courses > CourseAuditors".
Here's my query:
public void OnGet()
{
Departments = ctx.Departments.ToList();
foreach (var department in Departments)
{
department.Courses = ctx.Courses
.Where(c => c.DepartmentID == department.ID)
.ToList();
foreach (var course in department.Courses)
{
course.CourseAuditors = ctx.CourseAuditors
.Where(c => c.CourseID == course.ID)
.ToList();
}
}
}
Q: Is there any way I can get rid of the loops, and read everything in one query?
Here are the models:
Department.cs
public class Department
{
public int ID { get; set; }
public string Name { get; set; }
public string DepartmentHead { get; set; }
public virtual ICollection<Course> Courses { get; set; }
}
Course.cs
public class Course
{
public int ID { get; set; }
public string Name { get; set; }
public string Instructor { get; set; }
public string Location { get; set; }
public int DepartmentID { get; set; }
public virtual ICollection<CourseAuditor> CourseAuditors { get; set; }
}
CourseAuditor.cs
public class CourseAuditor
{
public int ID { get; set; }
public string StudentName { get; set; }
public int CourseID { get; set; }
}
Our current platform is
- TargetFramework=.net5.0;
- EntityFrameworkCore=5.0.6 (we'd like to migrate to .NET 6.x soon).
My primary concern is SQL-level efficiency (the fewer SQL-level queries/round trips the better!).
Any advice/suggestions would be welcome!