.Net Core(EF Core)中的多对多关系的最佳解决方案是什么? [英] what's the best solution for Many to Many Relation in .Net Core(EF Core)?

查看:105
本文介绍了.Net Core(EF Core)中的多对多关系的最佳解决方案是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在EF Core中没有自动的实体之间的多对多关系.什么是实现这一目标的最佳解决方案?在这里,我为此创造了东西:

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

推荐答案

在您的示例中,您做得正确,但是我想说 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; }
    }

这篇关于.Net Core(EF Core)中的多对多关系的最佳解决方案是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆