问题
as you know we don't have automatic Many to Many Relations between Entities in EF Core. whats the best solution to achieve that? here what I create for do that:
class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public string Family { get; set; }
public List<StudentCourse> Courses { get; set; }
}
class Course
{
public int CourseId { get; set; }
public string Name { get; set; }
public List<Student> Students { get; set; }
}
class StudentCourse
{
public int StudentCourseId { get; set; }
public Student Student { get; set; }
public Course Course { get; set; }
}
回答1:
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; }
}
来源:https://stackoverflow.com/questions/60992686/whats-the-best-solution-for-many-to-many-relation-in-net-coreef-core