In EF Core 10, what happens to a course's enrolments when the course is deleted, and how do OnDelete and DeleteBehavior change that?
answer
- two places a cascade runs
- required FK: Cascade by default
- optional FK: ClientSetNull by default
- only Cascade and SetNull reach the schema
- ClientCascade for tracked rows only
basics
~20 sWith the default required relationship (Cascade), EF Core deletes tracked enrolments itself and the database's ON DELETE CASCADE removes untracked ones. OnDelete(DeleteBehavior...) changes both what EF Core does to tracked rows and the constraint migrations create.
solid answer
~50 sCascading can happen in two places. For **tracked** dependents EF Core applies the configured behaviour itself; for rows it never loaded, only the **database constraint** can act. `Enrollment.CourseId` as an `int` makes the relationship required, so the default is `DeleteBehavior.Cascade`: EF Core sends a `DELETE` for each loaded enrolment before the course, and migrations create the foreign key with `ON DELETE CASCADE`, so unloaded enrolments go too. `OnDelete` changes that per relationship: `ClientCascade` deletes tracked dependents but leaves the constraint without an action; `SetNull` nulls the key in both places (nullable keys only); `ClientSetNull`, the optional default, nulls tracked keys only; `Restrict` and `NoAction` give the constraint no cascading action at all. Any non-cascading choice on a required relationship fails on save - an `InvalidOperationException` when the enrolments are loaded, a `DbUpdateException` from the database when they are not.
code
csharp · 11 lines// Required relationship, default Cascade: tracked enrolments are deleted by EF Core,
// untracked ones by the ON DELETE CASCADE constraint.
var course = await db.Courses.SingleAsync(c => c.Id == courseId);
db.Courses.Remove(course);
await db.SaveChangesAsync();
// Make deletion of a course with enrolments an error instead.
modelBuilder.Entity<Enrollment>()
.HasOne(e => e.Course)
.WithMany(c => c.Enrollments)
.OnDelete(DeleteBehavior.Restrict);go deeper
Remember that required relationships cascade deletes by default and that OnDelete with a DeleteBehavior value changes it.
Explain the split between tracked dependents, which EF Core handles, and unloaded rows, which only the constraint handles, and map each DeleteBehavior to both.
Diagnose the exceptions - InvalidOperationException for loaded dependents, DbUpdateException for unloaded ones - and choose behaviours that survive set-based deletes and provider limits.
Decide whether deletion rules live in the schema or the application, weighing physical cascades against soft delete, audit needs and multi-provider support.
## Two places a cascade can happen EF Core represents a relationship with a foreign key on the dependent. Deleting the principal - a `Course` - would leave each `Enrollment.CourseId` pointing at nothing, which the database's foreign key constraint rejects. There are two ways out: **delete the dependents** (cascade delete) or **set their foreign key to null** (only possible when the key is nullable). Either can happen in one of two places: - **In the change tracker.** EF Core always applies the configured behaviour to dependents it is **tracking**. When `SaveChanges` runs, it sends the `DELETE` or `UPDATE` statements for them. - **In the database.** When the schema is created by migrations or `EnsureCreated`, EF Core writes the behaviour into the foreign key constraint. That is the only thing that acts on rows the context never loaded. `DeleteBehavior` controls both at once, which is why the enum is confusing at first. ## What the default does `Enrollment.CourseId` declared as `int` makes the relationship **required**, and required relationships default to `DeleteBehavior.Cascade`: 1. Code calls `db.Courses.Remove(course)`; the course is marked `Deleted`. 2. Any tracked enrolments of that course are marked `Deleted` straight away (the `ChangeTracker.CascadeDeleteTiming` default is `CascadeTiming.Immediate`). 3. `SaveChanges` sends a `DELETE` per tracked enrolment, then the `DELETE` for the course. 4. Enrolments that were never loaded are removed by the database, because the constraint was created with `ON DELETE CASCADE`. If the key were `int?`, the relationship would be optional and default to `ClientSetNull`: tracked enrolments get `CourseId = null`, but the constraint has no action, so untracked ones make the delete fail. ## The DeleteBehavior values | Value | Tracked dependents | Constraint created | |---|---|---| | `Cascade` | deleted by EF Core | `ON DELETE CASCADE` | | `ClientCascade` | deleted by EF Core | no cascading action | | `SetNull` | foreign key set to null | `ON DELETE SET NULL` | | `ClientSetNull` | foreign key set to null | no cascading action | | `Restrict` | foreign key set to null if optional | `ON DELETE RESTRICT` (NO ACTION on SQL Server) | | `NoAction` | foreign key set to null if optional | database default | | `ClientNoAction` | left untouched | database default | Only `Cascade` and `SetNull` make the **database** cascade anything. `SetNull` cannot work on a required relationship, because the column is not nullable; SQL Server rejects such a constraint when the database is created. ## Non-cascading behaviour on a required relationship Choosing anything but `Cascade` or `ClientCascade` for a required relationship means deleting a course that still has enrolments fails: - **Enrolments loaded:** EF Core cannot null a non-nullable key, so `SaveChanges` throws `InvalidOperationException` reporting that the association has been severed. - **Enrolments not loaded:** EF Core sends only the course `DELETE`; the database refuses it, and `SaveChanges` wraps the error in `DbUpdateException`. That is sometimes exactly the intent: `Restrict` turns "you cannot delete a course with enrolments" into a schema rule. ## Configuring it ```csharp modelBuilder.Entity<Enrollment>() .HasOne(e => e.Course) .WithMany(c => c.Enrollments) .HasForeignKey(e => e.CourseId) .OnDelete(DeleteBehavior.Restrict); ``` Changing `OnDelete` changes the model, so the constraint only changes once a new migration is added and applied. ## Reading what a migration will create The quickest check is the generated migration. EF Core maps each `DeleteBehavior` to a `ReferentialAction` in the `AddForeignKey` or `CreateTable` call: - `Cascade` becomes `onDelete: ReferentialAction.Cascade`. - `SetNull` becomes `onDelete: ReferentialAction.SetNull`. - `Restrict` becomes `onDelete: ReferentialAction.Restrict`. - `ClientSetNull`, `ClientCascade`, `ClientNoAction` and `NoAction` all become `onDelete: ReferentialAction.NoAction` - which is why the client-side values are invisible in the schema. ## Traps - **Set-based deletes skip EF Core's half.** `ExecuteDeleteAsync` sends one `DELETE` without involving the change tracker, so only the database constraint acts: it works with `Cascade`, fails with `ClientCascade`. - **Soft delete and database cascades do not mix.** A physical cascade can really delete rows the application meant to keep and only flag. - **SQL Server refuses some cascades.** It rejects constraints that could form cycles or multiple cascade paths; `ClientCascade` keeps EF Core's behaviour without the database action, at the price of loading the dependents. - **PostgreSQL through Npgsql** accepts multi-path cascades, so the same model can migrate on one provider and fail on another.
- Why would a team choose ClientCascade over Cascade?When the database cannot or should not cascade - SQL Server refusing a constraint that creates multiple cascade paths, or a team that wants no physical cascades in the schema. EF Core still deletes tracked dependents, but the constraint has no action, so the code must load the enrolments first or the delete fails with a `DbUpdateException`.
- Does `db.Courses.Where(c => c.IsArchived).ExecuteDeleteAsync()` apply the DeleteBehavior?Only the database half. `ExecuteDeleteAsync` sends one `DELETE` without the change tracker, so EF Core cascades nothing itself. With `Cascade`, the `ON DELETE CASCADE` constraint removes the enrolments; with `ClientCascade`, `ClientSetNull` or `Restrict`, the database rejects the statement while enrolments exist.
- What does SetNull add over ClientSetNull for an optional relationship?Both null the key on tracked dependents. `SetNull` also creates the constraint with `ON DELETE SET NULL`, so rows the context never loaded are nulled by the database; with `ClientSetNull` those rows make the delete fail. SQL Server limits where `SET NULL` can be used without creating multiple cascade paths.
- EF Core loads a deleted course's enrolments by itself so it can cascade to them
- ClientSetNull writes ON DELETE SET NULL into the migration
- Restrict silently deletes the enrolments before the course
- ExecuteDeleteAsync applies the same client-side cascade as SaveChanges
- Cascade is the default for every relationship, optional ones included
- NoAction means the database lets the course row go without checking the constraint