在 多对多关系映射 中关联表是EF自动生成的。但有时候我们需要显示定义关联表。我们可以按照如下步骤定义(继续使用多对多关系映射这篇文章饿代码):
1. 定义关联表类:
public class StudentCourses : BaseEntity { public int StudentId { get; set; } public virtual Student Student { get; set; } public int CourseId { get; set; } public virtual Course Course { get; set; } }
2. 修改 Student 和 Courses 类中的导航属性:
public class Student:BaseEntity { public string Name { get; set; } public int Age { get; set; } public virtual ICollection<StudentCourses> StudentCourses { get; set; } } public class Course : BaseEntity { public string Name { get; set; } public string TeacherName { get; set; } public virtual ICollection<StudentCourses> StudentCourses { get; set; } }
3. 修改 StudentMap 和 CoursesMap 映射:
public class StudentsMap : EntityTypeConfiguration<Student> { public StudentsMap() { //表名称 ToTable("Students"); //主键 HasKey(p => p.Id); //设置主键自增长 Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); //设置要映射的数据 Property(p => p.Name).HasColumnType("VARCHAR").HasMaxLength(50); Property(p => p.Age); Property(p => p.CreateDateTime); //设置关系 HasMany(p => p.StudentCourses) .WithRequired(p => p.Student) .HasForeignKey(p => p.StudentId); } } public class CourseMap : EntityTypeConfiguration<Course> { public CourseMap() { ToTable("Coureses"); HasKey(p => p.Id); Property(p => p.Id) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(p => p.Name).HasColumnType("VARCHAR").HasMaxLength(50); Property(p => p.TeacherName); Property(p => p.CreateDateTime); HasMany(p => p.StudentCourses) .WithRequired(p => p.Course) .HasForeignKey(p => p.CourseId); } }
运行代码,查看数据库发现生成了同样的数据库,多对多关系也正确的反映出来。