且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.Net Core(EF Core)中的多对多关系的***解决方案是什么?

更新时间:2023-02-15 17:59:07

在您的示例中,您做得正确,但是我想说 Course 实体也应该有一个 List<StudentCourse> 而不是 List< Student 来保持一致.还将平面 CourseId 添加到 StudentCourse 实体,以控制映射配置中的外键.

In your example you're doing it correctly, but I would say that Course entity should also have a List<StudentCourse> rather than List<Student to keep it consistent. Also add flat CourseId to the StudentCourse entity to control the foreign key in mapping configuration.

使用联接表是一种常见的做法,并且EF Core中缺少自动"多对多关系,迫使您手动定义这些映射.

Using a join table is a common practice, and lack of the "automatic" many-to-many relations in EF Core forces you to define those mappings manually.

我个人喜欢EF Core中没有自动方式,因为它可以提供更多控制和整理表结构的功能(例如联接表的命名,强制组合主键等)

Personally I like that there is no automatic way in EF Core, because it gives more control and tidiness of table structure (like naming of the join table, forcing composite primary key etc.)

        public void Configure(EntityTypeBuilder<StudentCourse> builder)
        {
            builder.ToTable("StudentCourses");

            builder.HasKey(sc => new { sc.StudentId, sc.CourseId });  

            builder.HasOne(sc => sc.Student)
                .WithMany(s => s.StudentCourses)
                .HasForeignKey(sc => sc.StudentId);  

            builder.HasOne(sc => sc.Course)
                .WithMany(c => c.StudentCourses)
                .HasForeignKey(sc => sc.CourseId);
        }

    public class Student
    {
        public int StudentId { get; set; }

        public List<StudentCourse> StudentCourses { get; set; }
    }

    public class Course
    {
        public int CourseId { get; set; }

        public List<StudentCourse> 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; }
    }