在 ASP.NET Core 中,需要使用 Include() 方法来加载关联数据,确保关联数据已经被加载。例如,假设我们有一个 Student 和一个 Course 表,其中 Course 表有一个外键与 Student 表关联。我们可以通过以下方式在查询中加载关联数据:
var studentsAndCourses = _context.Students .Include(s => s.Course) .ToList();
在上面的示例中,我们使用了 Include() 方法来加载 Student 表和 Course 表之间的关联数据。如果我们没有使用 Include() 方法,查询将只返回 Student 表的数据,而 Course 的相应数据则不会被加载。
另外,如果您正在使用 Entity Framework Core,可以使用以下方式强制加载关联数据:
var students = _context.Students.ToList(); _context.Entry(students) .Collection(s => s.Course) .Load();
在上述示例中,我们使用了 Entity Framework Core 中的 Collection() 和 Load() 方法来强制加载与 Student 表关联的 Course 表数据。
通过上述方法,我们就可以在 ASP.NET Core 中加载关联数据了。