How to look forward to many of the many relationships with entity infrastructure code?

I will give the simplest example that I can present for the purpose of clarity.

Suppose I have two objects 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;} } 

These two objects are mapped to three tables, and the third to the table for joins.

When I speak to students like this

 var allStudents = context.Students; 

and then go to 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 request for each student who returns the first request.

How can I describe the infrastructure of an entity so that I can eagerly upload courses to students with just one request?

+3
source share
1 answer

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

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

Also make sure you have

 using System.Data.Entity; 

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

+10
source

All Articles