在多对多关系中,我们通常需要使用一个中间表来保存两个表之间的关系,这个中间表通常只包含两个外键。在 ASP .NET Core MVC 中,我们可以使用 Entity Framework Core 来映射多对多关系。
假设我们有两个实体类:Student 和 Course,它们之间有一个多对多关系。我们需要创建一个中间表来保存它们之间的关系。
首先,我们需要在我们的 DbContext 类中添加以下代码:
public DbSet StudentCourses { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasKey(sc => new { sc.StudentId, sc.CourseId });
modelBuilder.Entity()
.HasOne(sc => sc.Student)
.WithMany(s => s.StudentCourses)
.HasForeignKey(sc => sc.StudentId);
modelBuilder.Entity()
.HasOne(sc => sc.Course)
.WithMany(c => c.StudentCourses)
.HasForeignKey(sc => sc.CourseId);
}
在上面的代码中,我们定义了一个名为 StudentCourse 的新实体类,它代表中间表。我们在 DbContext 类中添加了一个 DbSet
接下来,我们在 OnModelCreating 方法中配置 StudentCourse 实体类的属性。我们设置主键为 StudentId 和 CourseId,这是中间表的两个外键。我们还定义了与 Student 和 Course 实体类的关系,并设置了外键。
现在,我们可以在 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; }