Single Fighter Single Fighter - 3 months ago 13
C# Question

How to iterate through the Enrollments navigation property of Student with EFCore?

I am using EFCore that seems to be unable to do lazy-loading in the current release.

My models are defined as follows:

public class Student
{
public int ID { get; set; }
public string FirstName { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}


public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }

public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}


public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }

public virtual ICollection<Enrollment> Enrollments { get; set; }
}


In
Details.cshtml
I want to iterate through the
Enrollments
of a student as follows.

@model ContosoUniversity.Models.Student
<h2>Details</h2>
<dl>
<dt>
@Html.DisplayNameFor(model => model.FirstMidName)
</dt>
<dd>
@Html.DisplayFor(model => model.FirstMidName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Enrollments)
</dt>
<dd>
<table>
<thead>
<tr>
<th>Course Title</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Enrollments)
{
<tr>
<td>@Html.DisplayFor(model => item.Course.Title)</td>
<td>@Html.DisplayFor(model => item.Grade)</td>
</tr>
}
</tbody>
</table>
</dd>
</dl>


However, I got the following errors.

enter image description here

Questions



How to fix this issue?

Answer

What you are trying to do is lazy loading. It is not supported by EF Core yet. Source

What you need to do, is when querying the database, use Include() to do eager loading.

So something like this:

var student = context.Students
                     .Include(s => s.Enrollments)
                     .ThenInclude(e => e.Course)
                     .FirstOrDefault(s => s.ID == id);
Comments