I am trying to get the correct mapping between 4 tables.
MainTables
Class(Id, ClassName)
Course(Id, CourseName)
Student(Id, StudentName)
Relationship tables
ClassCourse(Id, ClassId, CourseId)
ClassCourseStudent(ClassCourseId, StudentId)
Class to Course has Many to Many mapping. So we use a relationship table ClassCourse to store the relationship
Student has one to Many mapping with ClassCourse.
So my question is how can I do the mapping for Student and ClassCourse
My code is
public class Class
(
public int Id {get;set;}
public string ClassName {get;set;}
public virtual ICollection<Course> Courses {get;set;}
)
public class Course
(
public int Id {get;set;}
public string CourseName {get;set;}
public virtual ICollection<Student> Students {get;set;}
)
public class Student
(
public int Id {get;set;}
public string StudentName {get;set;}
)
modelBuilder.Entity<Class>().ToTable("Class");
modelBuilder.Entity<Course>().ToTable("Course");
modelBuilder.Entity<Student>().ToTable("Student");
modelBuilder.Entity<Class>().HasMany(c => c.Courses).WithMany().Map(m => m.ToTable("ClassCourse")
m.MapLeftKey("ClassId")
m.MapRightKey("CourseId")
)
modelBuilder.Entity<Course>().HasMany(c => c.Students).WithMany().Map(m =>
m.ToTable("ClassCourseStudent")
m.MapLeftKey("ClassCourseId")
m.MapRightKey("StudentId")
The last mapping is the one I am looking for.
Thanks in advance.