what's the best solution for Many to Many Relation in .Net Core(EF Core)? [duplicate]

江枫思渺然 提交于 2021-01-28 05:16:46

问题


as you know we don't have automatic Many to Many Relations between Entities in EF Core. whats the best solution to achieve that? here what I create for do that:

 class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public string Family { get; set; }
    public List<StudentCourse> Courses  { get; set; }

}
class Course
{
    public int CourseId { get; set; }
    public string Name { get; set; }
    public List<Student> Students { get; set; }
}
class StudentCourse
{
    public int StudentCourseId { get; set; }
    public Student Student { get; set; }
    public Course Course { get; set; }
}

回答1:


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.

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.

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; }
    }


来源:https://stackoverflow.com/questions/60992686/whats-the-best-solution-for-many-to-many-relation-in-net-coreef-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!