In EF Core 10, why does removing an enrolment from course.Enrollments delete its row on SaveChanges, and how do you move it to another course instead?
answer
- required key cannot hold null
- conceptual null after DetectChanges
- DeleteOrphansTiming defaults to Immediate
- re-parent through the reference or key
- CascadeTiming.OnSaveChanges defers orphan deletes
basics
~20 sThe Course-Enrollment relationship is required and cascades, so an enrolment removed from the collection becomes an orphan that EF Core marks Deleted. Move it by setting enrollment.Course or CourseId to the new course, not by removing it first.
solid answer
~40 sEF Core keeps navigations and foreign keys consistent - **fix-up**. When `DetectChanges` (called by `SaveChanges`) sees an enrolment missing from `course.Enrollments`, it severs the relationship: for an optional key it writes `null`, but a required `int CourseId` cannot hold null, so the enrolment is an **orphan**. With the default `Cascade`, EF Core marks orphans `Deleted` as soon as it detects them (`ChangeTracker.DeleteOrphansTiming` defaults to `CascadeTiming.Immediate`) and `SaveChanges` sends a `DELETE`. To move an enrolment, re-parent it directly: `enrollment.Course = target` or `enrollment.CourseId = target.Id`; fix-up updates both collections and only an `UPDATE` is sent. If code must remove and re-add, set `DeleteOrphansTiming = CascadeTiming.OnSaveChanges` so orphan deletion waits for `SaveChanges`. With `ClientSetNull` or `Restrict` on that required relationship, `SaveChanges` throws `InvalidOperationException` instead.
code
csharp · 13 linesvar course = await db.Courses
.Include(c => c.Enrollments)
.SingleAsync(c => c.Id == courseId);
var enrollment = course.Enrollments.Single(e => e.StudentId == studentId);
// Required, Cascade: this orphans the enrolment and SaveChanges deletes it.
course.Enrollments.Remove(enrollment);
// To move it instead, set the reference (or the key) and skip the Remove:
// enrollment.CourseId = targetCourseId;
await db.SaveChangesAsync();go deeper
Remember that removing a child from a required relationship's collection deletes it on save, and that setting the child's reference moves it instead.
Explain fix-up between keys and navigations, when DetectChanges notices list edits, and why a required key turns a removal into an orphan.
Diagnose unexpected deletes and severed-association exceptions in update handlers, and choose between re-parenting, DeleteOrphansTiming and CascadeChanges.
Decide whether a child's lifecycle should follow its collection membership at all, and make destructive changes explicit where accidental deletes cost the most.
## What fix-up is A relationship lives in two forms in memory: the **foreign key** value (`Enrollment.CourseId`) and the **navigations** (`Enrollment.Course`, `Course.Enrollments`). The database only has the key. EF Core's **relationship fix-up** keeps the two forms in step for tracked entities: - **On query** - entities materialised by a tracking query are connected to each other and to entities the context already tracks, using their key values. Fix-up never loads extra data; it only links what is present. - **On change** - when a navigation changes, EF Core updates the key and the inverse navigation; when a key changes, it moves the entity between collections. - **On detection** - with plain classes, edits to a `List<T>` are only noticed when `ChangeTracker.DetectChanges()` runs, which `SaveChanges` calls automatically. The examples assume an `Enrollment` with its own `Id` key, a required `int CourseId` and the default `DeleteBehavior.Cascade`. ## How a removal becomes a delete 1. Code calls `course.Enrollments.Remove(enrollment)` on a loaded collection. 2. `DetectChanges` sees the enrolment is gone and **severs** the relationship. 3. Severing means "no course", but `CourseId` is an `int`; EF Core records a **conceptual null**. 4. The relationship is required and set to cascade, so the enrolment is an **orphan**, and EF Core marks it `Deleted` at once. 5. `SaveChanges` sends a `DELETE` for it. Deleting orphans and cascade delete are the same rule seen from two sides: the parent was deleted, or the child was cut loose from a parent that still exists. | Relationship and behaviour | Removing the child from the collection | |---|---| | optional (`int?`), any null-setting behaviour | `UPDATE` sets the key to null | | required, `Cascade` or `ClientCascade` | child marked `Deleted`, `DELETE` sent | | required, `ClientSetNull`, `Restrict`, `NoAction` | `InvalidOperationException` on save | ## Moving an enrolment safely ```csharp // Re-parent directly: never an orphan, only an UPDATE is sent. enrollment.Course = targetCourse; // or enrollment.CourseId = targetCourse.Id; await db.SaveChangesAsync(); // Remove-then-add needs the orphan delete deferred. db.ChangeTracker.DeleteOrphansTiming = CascadeTiming.OnSaveChanges; sourceCourse.Enrollments.Remove(enrollment); targetCourse.Enrollments.Add(enrollment); await db.SaveChangesAsync(); ``` With `OnSaveChanges`, a severed child stays `Modified` with a conceptual null until `SaveChanges`; if it has been re-parented by then, it is updated rather than deleted. `CascadeTiming.Never` turns automatic orphan deletion off entirely: `SaveChanges` then throws for any tracked orphan unless code calls `ChangeTracker.CascadeChanges()` to apply the deletes at a moment it chooses. `CascadeDeleteTiming` is the matching setting for children of a **deleted** parent. ## Seeing what EF Core decided When a save does something unexpected, look at the change tracker before calling `SaveChanges`: - `db.ChangeTracker.DetectChanges()` forces detection of list edits made so far. - `db.ChangeTracker.DebugView.LongView` prints every tracked entity with its state, key values and navigations. - A severed required child shows its foreign key as `<null>` with "Modified Originally" and the old value - the conceptual null - or the state `Deleted` once orphan deletion has run. - `db.Entry(enrollment).State` answers the same question for one entity. ## The exception you meet in production When the relationship is required but configured without cascade, severing fails on save with an `InvalidOperationException`: the association between the two entity types "has been severed, but the relationship is either marked as required or is implicitly required because the foreign key is not nullable". The fix depends on intent: cascade if removal should delete, re-parent if it should move, or make the key nullable if an enrolment may exist without a course. ## Traps in update handlers - **Rebuilding a collection from a DTO.** Clearing `course.Enrollments` and adding new instances orphans every existing row, and new instances that reuse tracked keys conflict with the instances already tracked. - **Expecting removal to reach unloaded rows.** Only enrolments present in the loaded collection can be severed; rows the query did not load are untouched. - **Turning off `AutoDetectChangesEnabled`.** `SaveChanges` then never sees list edits unless code calls `DetectChanges` itself. - **Moving a child through two contexts.** Removing in one `DbContext` and adding in another gives each context only half the story; do the move in one unit of work. - **Assuming optional means safe.** On an optional relationship the same removal writes `null` instead of deleting, which may leave rows that no screen ever shows again.
- What does fix-up do when a second query returns enrolments of a course the context already tracks?It links them: each enrolment's `Course` points at the tracked course instance, and they are added to its `Enrollments` collection, without any extra query. Fix-up only connects entities that are already in the context or in the results; it never loads more.
- Why would a team set DeleteOrphansTiming to CascadeTiming.Never?To make deletion an explicit act. With `Never`, a tracked orphan makes `SaveChanges` throw instead of quietly deleting a row, which catches accidental removals in update handlers. When deletion is intended, code calls `ChangeTracker.CascadeChanges()` to mark orphans and cascades `Deleted` at that point.
A school office where every pupil's file must name a class register: crossing a pupil off one register without naming another makes the office treat the file as withdrawn and shred it, while changing the register written on the file itself is a simple transfer.
- Removing an entity from a navigation collection never changes the database
- Only DbSet.Remove can produce a DELETE statement
- A required foreign key is set to zero when the child is removed from the collection
- CascadeDeleteTiming controls when removed children become orphans
- Fix-up queries the database to fill navigations that were not loaded