Reputation: 2991
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?
Upvotes: 4
Views: 4026
Reputation: 160882
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.
Upvotes: 12