Association tables are automatically generated by EF in multi-to-multi relational mapping. But sometimes we need to show the associated tables that define them. We can define it in the following steps (continue using the hungry code in this article on multi-to-many mapping):
- Define association table classes:
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; } }
- Modify navigation attributes in Student and Courses classes:
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; } }
- Modify StudentMap and CoursesMap mappings:
public class StudentsMap : EntityTypeConfiguration<Student> { public StudentsMap() { //Table Name ToTable("Students"); //Primary key HasKey(p => p.Id); //Setting Primary Key Self-growth Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); //Setting up the data to be mapped Property(p => p.Name).HasColumnType("VARCHAR").HasMaxLength(50); Property(p => p.Age); Property(p => p.CreateDateTime); //set relationship 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); } }
Running the code, looking at the database found that the same database was generated, and many-to-many relationships were also correctly reflected.