Entity Framework Core Interview Question #31

What is a many-to-many relationship in EF Core?

Relationships, Navigation Properties & Loading Data Junior Beginner

Quick Interview Answer

A many-to-many relationship means each entity on either side can relate to multiple entities on the other side. For example, a Student can take many Courses and a Course can have many Students.

Detailed Explanation

A many-to-many relationship means each entity on either side can relate to multiple entities on the other side. For example, a Student can take many Courses and a Course can have many Students.

EF Core can manage a join table automatically for simple many-to-many relationships when collection navigations exist on both sides.

When the relationship itself contains additional data such as EnrolledAt, Quantity, Role, or SortOrder, model the join table as an explicit entity.

Code Example

public class Student
{
    public int Id { get; set; }
    public ICollection<Course> Courses { get; set; } = new List<Course>();
}

public class Course
{
    public int Id { get; set; }
    public ICollection<Student> Students { get; set; } = new List<Student>();
}