如果在 ASP.NET Core 中遇到多对多关系的问题,可以使用以下方法进行解决。例如,考虑两个实体类 Student
和 Course
,它们之间有一个多对多的关系。这里给出了不包括关联的实体类代码:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection StudentCourses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection StudentCourses { get; set; }
}
public class StudentCourse
{
public int StudentId { get; set; }
public Student Student { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
}
这里需要注意的是,关联实体类 StudentCourse
中需要包含两个外键和两个相关的导航属性。
如果要在查询中包含关联的实体,可以使用 Include
方法。例如,以下代码演示了如何查询名为'John”的学生及其所选的所有课程:
var student = await _context.Students
.Include(s => s.StudentCourses)
.ThenInclude(sc => sc.Course)
.SingleOrDefaultAsync(s => s.Name == "John");
在上面的查询中,我们使用 Include
方法将 StudentCourses
包含在内,并使用 ThenInclude
方法将 Course
包含在内。注意,ThenInclude
方法只适用于嵌套的导航属性。如果查询中有多个关联,可以使用多个 Include
方法。