In your example you're doing it correctly, but I would say that Course
entity should also have a List<StudentCourse>
rather than List<Student
to keep it consistent. Also add flat CourseId
to the StudentCourse
entity to control the foreign key in mapping configuration.
Using a join table is a common practice, and lack of the "automatic" many-to-many relations in EF Core forces you to define those mappings manually.
Personally I like that there is no automatic way in EF Core, because it gives more control and tidiness of table structure (like naming of the join table, forcing composite primary key etc.)
public void Configure(EntityTypeBuilder<StudentCourse> builder)
{
builder.ToTable("StudentCourses");
builder.HasKey(sc => new { sc.StudentId, sc.CourseId });
builder.HasOne(sc => sc.Student)
.WithMany(s => s.StudentCourses)
.HasForeignKey(sc => sc.StudentId);
builder.HasOne(sc => sc.Course)
.WithMany(c => c.StudentCourses)
.HasForeignKey(sc => sc.CourseId);
}
public class Student
{
public int StudentId { get; set; }
public List<StudentCourse> StudentCourses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public List<StudentCourse> StudentCourses { get; set; }
}
public class StudentCourse
{
public int StudentId { get; set; }
public Student Student { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
}