skip to content

In EF Core 10, when is a Student-Course many-to-many mapped with skip navigations alone, and when does it need an Enrollment join entity through UsingEntity?

level: middleimportance: should knowfreq 55%

answer

  1. two collections, no join class
  2. shared-type entity, Dictionary<string, object>
  3. CourseStudent table by convention
  4. payload means a join class
  5. UsingEntity<Enrollment>() keeps skip navigations

basics

~20 s

With only Student.Courses and Course.Students, EF Core creates a hidden shared-type join entity and a CourseStudent table. Once the link carries data such as an enrolment date or grade, map an Enrollment class with UsingEntity<Enrollment>().

solid answer

~50 s

A collection on each side - `Student.Courses` and `Course.Students` - is enough: EF Core treats them as **skip navigations** and creates an implicit join entity, a shared-type entity backed by `Dictionary<string, object>`, mapped to a `CourseStudent` table with a composite primary key and two cascading foreign keys. You add and remove links through the collections and never see the join row. As soon as the link has data of its own - `EnrolledOn`, `Grade` - you need a class: `HasMany(s => s.Courses).WithMany(c => c.Students).UsingEntity<Enrollment>()`. The skip navigations keep working, and you can add navigations to `Enrollment` beside them. One catch: when you link through `student.Courses.Add(course)`, EF Core creates the `Enrollment` without setting payload, so give generated payload a database default and add the `Enrollment` yourself when a value such as the grade must be set.

code

csharp · 11 lines
csharp
// Link through the skip navigation; EF Core creates the Enrollment row.
student.Courses.Add(course);
// Local runs DetectChanges, so the new join instance is there.
var enrollment = db.Set<Enrollment>().Local
    .Single(e => e.StudentId == student.Id && e.CourseId == course.Id);
enrollment.Grade = "pending";

// Or create the join entity directly; skip navigations are fixed up.
db.Add(new Enrollment { StudentId = student.Id, CourseId = other.Id, Grade = "pending" });

await db.SaveChangesAsync();

go deeper

for a junior

Recall that two collection navigations are enough for EF Core to build a join table, and that a class is needed once the link carries data.

for a middle

Explain skip navigations, the shared-type join entity and its CourseStudent table, and how UsingEntity<Enrollment>() maps a payload while keeping the collections.

for a senior

Choose between the three mapping shapes from the domain, handle payload when links are added through skip navigations, and spot the retake case the composite key forbids.

for a principal

Judge when the enrolment deserves to be a first-class entity with its own rules and lifecycle instead of an implementation detail behind two collections.

## Why many-to-many needs a join table A relational database cannot hold a many-to-many link in one foreign key: a student takes many courses and a course has many students. The link lives in a **join table** whose rows each pair one student with one course. EF Core always models that table as a **join entity type** with two one-to-many relationships - one to `Student`, one to `Course`. The only question is whether your code sees it. ## Skip navigations alone Give each side a collection and nothing else: - `Student.Courses` and `Course.Students` are **skip navigations**: they skip over the join entity to reach the other side. - EF Core creates the join entity for you as a **shared-type entity type** whose instances are currently `Dictionary<string, object>` (the docs warn not to depend on that type). - By convention the join type is named from the two entity names in ordinal order, so the table is `CourseStudent`, with one foreign key column per side and a composite primary key over both. - Both foreign keys are created with **cascade delete**: deleting a student removes its join rows, never the courses. - `UsingEntity("StudentCourses")` can rename the join while keeping it implicit. This is the right mapping when the link is a pure fact - "this student takes this course" - with nothing else to record. ## When the link needs a class Real enrolment systems record data about the link itself: when the student enrolled, the grade, the status. That data is a **payload**, and a payload needs a CLR type: ```csharp public class Enrollment { public int StudentId { get; set; } public int CourseId { get; set; } public DateTime EnrolledOn { get; set; } public string? Grade { get; set; } } modelBuilder.Entity<Student>() .HasMany(s => s.Courses) .WithMany(c => c.Students) .UsingEntity<Enrollment>( j => j.Property(e => e.EnrolledOn).HasDefaultValueSql("now()")); // PostgreSQL ``` `StudentId` and `CourseId` are picked up as the foreign keys and as the composite key. The overloads of `UsingEntity` that take a left and a right lambda configure the two one-to-many halves explicitly, for non-conventional key names or a non-cascading delete. ## Three shapes compared | Shape | Join class | Skip navigations | Use when | |---|---|---|---| | Skip navigations only | none (shared-type) | yes | the link has no data | | `UsingEntity<Enrollment>()` | yes | yes | the link has payload but code mostly walks student-to-course | | Plain entity, two one-to-many | yes | no | the enrolment is a first-class concept with its own rules | The third shape needs no many-to-many configuration at all: `Enrollment` has `Student` and `Course` references, and `Student.Enrollments` / `Course.Enrollments` collections. ## Setting payload values Adding a link through a skip navigation makes EF Core create the join entity instance itself, so it cannot know your payload: 1. **Generated values** - `HasDefaultValueSql` or a value generator fills `EnrolledOn` without any code. 2. **Find the join entity** - after `student.Courses.Add(course)`, look the new instance up in `db.Set<Enrollment>().Local`, which runs `DetectChanges` first, and set `Grade`. 3. **Add the join entity yourself** - `db.Add(new Enrollment { StudentId = s, CourseId = c, Grade = "A" })`; the skip navigations are fixed up to match. ## Querying through skip navigations Skip navigations work in LINQ like any collection navigation. `db.Students.Where(s => s.Courses.Any(c => c.Title == "Chemistry"))` is translated with the join table in the SQL, and a projection such as `s.Courses.Count()` counts join rows without loading courses. With a join class mapped, `db.Set<Enrollment>()` additionally exposes the payload: filtering enrolments by `EnrolledOn` or grouping them by `Grade` reads the join table directly. ## Removing links - `student.Courses.Remove(course)` on a loaded collection marks the join row `Deleted`; the student and course rows stay. - Removing an `Enrollment` entity has the same effect. - Changing a composite key value is not allowed, so moving an enrolment means removing one row and adding another. ## Common mistakes - Writing code against the implicit join's `Dictionary<string, object>` instances; the docs reserve the right to change that type, so map a class if code needs the join. - Expecting payload to appear when linking through `student.Courses`. - Using the composite key when a student may retake a course; that needs a join entity with its own primary key or the plain-entity shape.

  • Can code use student.Courses and also query enrolments directly?
    Yes. Add `Student.Enrollments` and `Course.Enrollments` collections, and navigations from `Enrollment` back to both sides; conventions attach them to the same join entity, or `UsingEntity`'s left and right lambdas pair them explicitly. `db.Set<Enrollment>()` then queries the join rows with their payload, while the skip navigations still read as plain student-to-course collections.
  • What changes if a student may enrol in the same course twice, for a retake?
    The composite primary key over `StudentId` and `CourseId` forbids a second row for the pair. Give `Enrollment` its own primary key and keep the two foreign keys as ordinary columns, or drop the many-to-many mapping and treat `Enrollment` as a plain entity with two one-to-many relationships.

  • EF Core cannot map many-to-many without a join class in the model
  • Linking through student.Courses fills the Enrollment payload from defaults in C#
  • Removing a course from student.Courses deletes the course row
  • UsingEntity<Enrollment>() removes the skip navigations, so only Enrollment can be used
  • The implicit join entity is a hidden class EF Core generates at compile time