C# – Read related data – ASP.NET MVC with EF Core – Video

After creating a complex data model, now it is time to display the data, following the tutorial.

C# – Read related data - ASP.NET MVC with EF Core

The task is actually a challenging one, as far as the data display is in a way partial – in the  “Instructors” view, the instructors are selectable and their courses are displayed. Then the courses are also selectable and the students enlisted are displayed:

Achieving this is actually not a trivial task at all. This is how the Index() method of the InstructorsController.cs looks like:

public async Task Index(int? id, int? courseId)
{
	var viewModel = new InstructorIndexData();
	viewModel.Instructors = await _context.Instructors
		.Include(i => i.OfficeAssignment)
		.Include(i => i.CourseAssignments)
			.ThenInclude(i => i.Course)
				.ThenInclude(i => i.Enrollments)
					.ThenInclude(i => i.Student)
		.Include(i => i.CourseAssignments)
			.ThenInclude(i => i.Course)
				.ThenInclude(i => i.Department)
		.OrderBy(i => i.LastName)
		.ToListAsync();

	if (id != null)
	{
		ViewData["InstructorId"] = id.Value;
		Instructor instructor = viewModel.Instructors.Where(i => i.ID == id.Value).Single();
		viewModel.Courses = instructor.CourseAssignments.Select(s => s.Course);
	}

	if (courseId != null)
	{
		ViewData["CourseId"] = courseId.Value;
		var selectedCourse = viewModel.Courses.Where(x => x.CourseId == courseId).Single();
		await _context.Entry(selectedCourse).Collection(x => x.Enrollments).LoadAsync();
		foreach (Enrollment enrollment in selectedCourse.Enrollments)
		{
			await _context.Entry(enrollment).Reference(x => x.Student).LoadAsync();
		}
		viewModel.Enrollments = selectedCourse.Enrollments;
	}
	return View(viewModel);
}

It “controls” the Index.cshtml view, which is quite complicated as well. The 2 ifs at the end of the code –  @if (Model.Courses != null) and @if (Model.Enrollments != null) show whether the “Select” link is clicked or not. Additionally, I liked the way the CSS class is passed for the row as a string. There is something nice in it:

@foreach (var item in Model.Instructors)
{
	string selectedRow = "";
	if (item.ID == (int?)ViewData["InstructorId"])                 
	{
		selectedRow = "success";
	}
	<tr class="@selectedRow">

For everything else, the GitHub code is here: https://github.com/Vitosh/ASP/tree/master/EFCoreAsp.NetMvcWebApp/ContosoUniversity006

Enjoy it! 🙂