This excerpt code successfully creates a many-many relationship with an explicit Junction table that has additional data within it.
PROBLEM:
Entity Framework can't automatically determine 'many-to-many' relations because they are expressed with the help of additional tables in SQL (in your case it is Enrollment
table). You can specify mappings directly in OnModelCreating
method:
public class YourDbContext : DbContext
{
....
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().HasMany(x => x.Courses).WithMany(x => x.Students)
.Map(m =>
{
m.ToTable("Enrollment"); // Relationship table name
m.MapLeftKey("StudentID"); // Name of column for student IDs
m.MapRightKey("CourseID"); // Name of column for course IDs
});
}
}
Also, take a note that if an entity have many other entities, use collection for relationship:
public class Student
{
....
public virtual ICollection Courses { get; set; } // Many courses
}
public class Course
{
....
public virtual ICollection Students { get; set; } // Many students
}