在.NET Entity Framework Core(EF Core)中,實現(xiàn)多對多關(guān)系需要遵循以下步驟:
Student
和Course
實體,一個學生可以選修多門課程,一門課程也可以被多個學生選修。public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<StudentCourse> StudentCourses { get; set; }
}
StudentCourse
的實體。public class StudentCourse
{
public int StudentId { get; set; }
public Student Student { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
}
DbContext
類中,使用ModelBuilder
配置多對多關(guān)系。我們需要指定關(guān)聯(lián)表實體,并設(shè)置外鍵。public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<StudentCourse> StudentCourses { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StudentCourse>()
.HasKey(sc => new { sc.StudentId, sc.CourseId });
modelBuilder.Entity<StudentCourse>()
.HasOne<Student>(sc => sc.Student)
.WithMany(s => s.StudentCourses)
.HasForeignKey(sc => sc.StudentId);
modelBuilder.Entity<StudentCourse>()
.HasOne<Course>(sc => sc.Course)
.WithMany(c => c.StudentCourses)
.HasForeignKey(sc => sc.CourseId);
}
}
現(xiàn)在,你已經(jīng)在EF Core中實現(xiàn)了多對多關(guān)系。你可以使用DbContext
類來查詢、添加、更新和刪除相關(guān)數(shù)據(jù)。