Besides a dedicated join entity, how can you configure a many-to-many relationship in EF Core 5+ and what are the benefits of this approach?

.NET interview question for Advanced practice.

Answer

In EF Core 5.0 and later, many-to-many relationships can be configured using skip navigations, which do not require a dedicated join entity in your C model. The join table still exists in the database, but EF Core manages it implicitly. Example Models: csharp public class Student { public int StudentId { get; set; } public string Name { get; set; } // Skip navigation property public ICollection<Course Courses { get; set; } } public class Course { public int CourseId { get; set; } public string Title { get; set; } // Skip navigation property public ICollection<Student Students { get; set; } } Benefits of this approach: 1. Simpler Model: Your domain model is cleaner as it doesn't need a StudentCourse class, reflecting the business entities more directly. 2. Intuitive Usage: You can add and remove relationships more naturally. For example, to enroll a student in a course, you can simply do student.Courses.Add(course);. 3. Convention-Based: In many cases, no explicit configuration is needed. EF Core will recognize the relationship by convention and create the join table in the database automatically. This approach is ideal when the relationship itself doesn't contain any additional data (payload). If you need to store information like EnrollmentDate, you would still need to create an explicit join entity.

Explanation

Even when using skip navigations, you can still customize the underlying join table, for example, to change its name or the names of the foreign key columns, using the UsingEntity method in Fluent API.

Related Questions