Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eagerly load a many to many relationship with the entity framework code first?

I'll give the most basic example that I can think of for the purpose of clarity.

Lets say that I have two entities of the following form:

public class Student
{
    public int Id {get;set}
    public string FullName {get;set;}
    public virtual ICollection<Course> Courses {get;set;}
}

public class Courses
{
    public int Id {get;set;}
    public string FullName {get;set;}
    public virtual ICollection<Student> Students {get;set;}
}

Those two entities map to three tables, the third one being a table for the joins.

When I query the Students like this

var allStudents = context.Students;

and then traverse the results to display a list of students and their courses like this

foreach (var student in allStudents) 
{
    display(student.FullName);
    foreach (var course in student.Courses) 
    {
        display(course.FullName);
    }
}

I get a Course query for each Student that the first query returned.

How do I tell the entity framework to eagerly load the courses into the students with just one query?

like image 995
adolfojp Avatar asked Dec 16 '22 14:12

adolfojp


1 Answers

You want an Include() query to indicate that you want to eagerly load the related Course entities:

var allStudents = context.Students.Include( s => s.Courses);

Also make sure you have a

using System.Data.Entity;

in your code file so you can use the strongly typed Include() extension method.

like image 200
BrokenGlass Avatar answered Dec 19 '22 05:12

BrokenGlass