Below is a snippet of code of a little practice project. I am still pretty new to EF and I was wondering if there is a way to write the below statement so that all required data is eager loaded since I have the ID parameter.
public ActionResult Index(int? id)
{
var viewModel = new InstructorIndexData
{
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.Single(i => i.InstructorId == id.Value).Courses;
}
return View(viewModel);
}
When this action runs it grabs the instructor data and includes a few other collections because they are required for the initial view of the page. After selecting an instructor the page comes back with the instructor and the course the instructor is assigned to but this requires two calls to the database. Is there a way I can simple add the course to the initial query before it goes out to pull the instructor since that doesnt occur till the return?