4

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?

adolfojp
  • 2,961
  • 4
  • 24
  • 21

1 Answers1

12

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.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • 1
    Phenomenal. It works. :-D I hadn't included the System.Data.Entity at the top so I didn't even know that I had a strongly typed extension method available. – adolfojp May 01 '11 at 20:49
  • @adolfojp: Yea that's a new addition (EF 4.1 release and in the CTPs before that), it really helps to avoid magic strings :-) – BrokenGlass May 01 '11 at 21:28
  • 2
    If there are either many items on each side (and much relationships between them) or both sides contain large binary blobs then such a query will last a long time and will transfer gigabytes of redundant data. – springy76 Nov 30 '12 at 17:04