一对多和一对一都只需要在表中增加外键列,但是在多对多关系中,我们必须引入一张中间表保存两张表之间的关联关系。
多对多:不需要声明中间表实体,也不需要声明外键。
实体:
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); } }
标签:Core,set,Name,配置,get,builder,EF,Teachers,public From: https://www.cnblogs.com/friend/p/16744903.html