I'm reading the Microsft tutorial about Asp.Net MVC 5 and EF 6 at this link text . Now I'm confused with the code below.
public ActionResult Index(int? id, int? courseID)
{
var viewModel = new InstructorIndexData();
viewModel.Instructors = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName);
if (id != null)
{
ViewBag.InstructorID = id.Value;
viewModel.Courses = viewModel.Instructors.Where(
i => i.ID == id.Value).Single().Courses;
}
if (courseID != null)
{
ViewBag.CourseID = courseID.Value;
viewModel.Enrollments = viewModel.Courses.Where(
x => x.CourseID == courseID).Single().Enrollments;
}
return View(viewModel);
}
public class InstructorIndexData
{
public IEnumerable<Instructor> Instructors { get; set; }
public IEnumerable<Course> Courses { get; set; }
public IEnumerable<Enrollment> Enrollments { get; set; }
}
I thought that these lines of code would load **all **Instructors and for each one the related OfficeAssignment and **all **instructor's Courses with Department related to each Course.
viewModel.Instructors = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName);
If so, why after, if an Instructor is seleted (id!=null), the viewmodel Courses are loaded again?
viewModel.Courses = viewModel.Instructors.Where(i => i.ID == id.Value).Single().Courses;
Can someone, please, explain?
The first load is to load all the Instructors and their related OfficeAssigments and Courses from the database into the Instructors property of viewModel, just like your understanding, so this is the eager loading part, where all relevant data is fetched from the database.
The second load is to load all the related Courses to the selected Instructor from the Instructors property of viewModel (which was fetched in part1), to the Courses property of viewModel. So this part is not fetching from the database at all, allowing you to not have to open another connection to the database.