学海无涯

导航

EF Core 关系配置 多对多

一对多和一对一都只需要在表中增加外键列,但是在多对多关系中,我们必须引入一张中间表保存两张表之间的关联关系。

多对多:不需要声明中间表实体,也不需要声明外键。

实体:

 public class Teacher
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public List<Student> Students { get; set; }=new List<Student>();
    }

  

public class Student
    {
        public long Id { get; set; }
        public string Name { get; set; }    
        public List<Teacher> Teachers { get; set; }
    }

  表结构:

 

 

 

 

 配置类:

 public class TeacherConfig : IEntityTypeConfiguration<Teacher>
    {
        public void Configure(EntityTypeBuilder<Teacher> builder)
        {
            builder.ToTable("T_Teachers");
            builder.Property(s => s.Name).HasMaxLength(20);
            builder.HasMany<Student>(t => t.Students).WithMany(s => s.Teachers)
                .UsingEntity(m => m.ToTable("T_Students_Teachers"));
        }
    }

  

public class StudentConfig : IEntityTypeConfiguration<Student>
    {
        public void Configure(EntityTypeBuilder<Student> builder)
        {
            builder.ToTable("T_Students");
            builder.Property(s => s.Name).IsUnicode().HasMaxLength(20);
        }
    }

  

posted on 2022-09-30 14:50  宁静致远.  阅读(470)  评论(0编辑  收藏  举报