A Many-to-Many relationship occurs when multiple records in one table associate with multiple records in another. A classic example: A Student takes many Courses, and a Course enrolls many Students. Relational databases cannot natively store Many-to-Many relationships; they require a "Join Table" in the middle.
In modern EF Core, if you simply define collections on both entities, the framework is smart enough to automatically generate the hidden SQL Join Table behind the scenes during migrations!
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
// A Student has many Courses
public ICollection<Course> Courses { get; set; } = new List<Course>();
}
public class Course
{
public int Id { get; set; }
public string Title { get; set; }
// A Course has many Students
public ICollection<Student> Students { get; set; } = new List<Student>();
}
dotnet ef migrations add, EF Core will physically create three tables in SQL Server: Students, Courses, and a hidden join table named CourseStudent containing the two foreign keys.
The implicit magic is great, but what if you need to store extra data about the relationship itself? For example, what Grade did the student get in that specific course? A hidden join table cannot store a Grade. You must explicitly model the Join Table as a C# class.
public class Enrollment // The explicit Join Table!
{
public int StudentId { get; set; }
public Student Student { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
// The Payload Data!
public string Grade { get; set; }
public DateTime EnrollmentDate { get; set; }
}
public class Student
{
public int Id { get; set; }
// Now it points to the Join Entity, not directly to Course!
public ICollection<Enrollment> Enrollments { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Enrollment>>()
// The join table MUST have a composite primary key
.HasKey(e => new { e.StudentId, e.CourseId });
}
Q: "When using the Implicit Many-to-Many setup, how do I actually add a new student to an existing course using C# code without touching SQL?"
Architect Answer: "Because EF Core manages the hidden join table completely natively, you construct the relationship purely through Object-Oriented C# interactions. First, you load the `Student` from the database. Next, you load the `Course` from the database. Then, you simply add the object to the collection: `student.Courses.Add(course);`. Finally, you call `await _context.SaveChangesAsync();`. The EF Core Change Tracker detects that a new object was inserted into the Navigation Collection and automatically translates that action into a physical `INSERT` statement into the hidden `CourseStudent` SQL junction table."