skip to content

Deleting an EF Core 10 student who mentors other students throws DbUpdateException although Student.MentorId is nullable - why, and how do you fix it?

level: seniorimportance: should knowfreq 30%

answer

  1. a self-reference is just one-to-many
  2. optional default: ClientSetNull
  3. no ON DELETE action in the schema
  4. unloaded mentees still hold the key
  5. SetNull versus SQL Server's cycle rule

basics

~20 s

The self-referencing Mentor relationship is optional, so its default ClientSetNull nulls MentorId only on tracked mentees; the constraint has no ON DELETE action, so unloaded mentees still reference the row. Load the mentees, or configure OnDelete(DeleteBehavior.SetNull).

solid answer

~50 s

`Student.Mentor` / `Student.Mentees` is an ordinary one-to-many whose principal and dependent are the same type, configured with `HasOne(s => s.Mentor).WithMany(s => s.Mentees).HasForeignKey(s => s.MentorId)`. Because `MentorId` is `int?`, the relationship is optional and defaults to `DeleteBehavior.ClientSetNull`: EF Core sets `MentorId = null` on mentees it **tracks**, but migrations create the constraint without an `ON DELETE` action. Delete a mentor without loading the mentees and only the `DELETE` is sent; the database rejects it and `SaveChanges` wraps the error in `DbUpdateException`. Fixes: `Include(s => s.Mentees)` before `Remove`, so EF Core sends the `UPDATE`s first; or `OnDelete(DeleteBehavior.SetNull)`, which PostgreSQL accepts as `ON DELETE SET NULL` - SQL Server refuses it on a self-reference as a possible cycle, so there you load the mentees or null their key with a set-based update in the same transaction. `Cascade` would delete the mentees too.

code

csharp · 13 lines
csharp
// Fix 1: load the mentees so ClientSetNull can null their key.
var mentor = await db.Students
    .Include(s => s.Mentees)
    .SingleAsync(s => s.Id == id);
db.Students.Remove(mentor);
await db.SaveChangesAsync();   // UPDATE each mentee, then DELETE

// Fix 2 (PostgreSQL): let the database null it via a migration.
modelBuilder.Entity<Student>()
    .HasOne(s => s.Mentor)
    .WithMany(s => s.Mentees)
    .HasForeignKey(s => s.MentorId)
    .OnDelete(DeleteBehavior.SetNull);

go deeper

for a junior

Recall that a self-reference is configured like any one-to-many, with HasOne, WithMany and HasForeignKey on the same entity type.

for a middle

Explain why ClientSetNull only touches tracked dependents and how that turns an unloaded mentee into a database error.

for a senior

Pick the fix by provider and data size - loading, SetNull, or a set-based update in one transaction - and recognise SQL Server's cycle rule when a migration fails.

for a principal

Decide whether hierarchy cleanup belongs in the schema or in application code when the same model must run on providers with different cascade rules.

## A self-reference is an ordinary relationship A **self-referencing** relationship has the same entity type at both ends. A peer-mentoring scheme in a school system is the classic shape: each student may have one mentor, who is also a student, and a mentor may have many mentees. ```csharp public class Student { public int Id { get; set; } public string Name { get; set; } = ""; public int? MentorId { get; set; } public Student? Mentor { get; set; } public List<Student> Mentees { get; } = []; } modelBuilder.Entity<Student>() .HasOne(s => s.Mentor) .WithMany(s => s.Mentees) .HasForeignKey(s => s.MentorId); ``` Nothing about it is special to EF Core: `Mentor` points from dependent to principal, `Mentees` is the inverse collection, and `MentorId` is a foreign key column on the `Students` table referencing the same table. Conventions can discover it, but explicit configuration avoids ambiguity when a type has several self-references (mentor, tutor, buddy). ## Why the delete fails 1. `MentorId` is `int?`, so the relationship is **optional**. 2. Optional relationships default to `DeleteBehavior.ClientSetNull`. 3. `ClientSetNull` acts in the change tracker only: tracked mentees get `MentorId = null`. 4. In the schema it creates the foreign key with the database default, no cascading action. 5. The handler loads only the mentor and calls `Remove`; `SaveChanges` sends a single `DELETE`. 6. Rows in `Students` still reference that id, so the database rejects the statement and `SaveChanges` throws `DbUpdateException`. A nullable key makes nulling **possible**; it does not make the database do it. ## The fixes | Fix | What runs | PostgreSQL | SQL Server | |---|---|---|---| | `Include(s => s.Mentees)` before `Remove` | `UPDATE` per mentee, then `DELETE` | works | works | | `OnDelete(DeleteBehavior.SetNull)` | database nulls `MentorId` | `ON DELETE SET NULL` accepted | constraint refused (possible cycle) | | set-based update, then delete, in one transaction | one `UPDATE`, one `DELETE` | works | works | | `OnDelete(DeleteBehavior.Cascade)` | mentees deleted too | works | constraint refused | Points that decide between them: - **Loading** is simple and provider-neutral but costs a query and memory per mentee. - **SetNull** moves the rule into the schema, so unloaded rows are handled too - on providers that allow it. - **A set-based update** (`ExecuteUpdateAsync` setting `MentorId` to null for the mentor's mentees) bypasses the change tracker; run it in the same transaction as the delete. - **Cascade** is almost never right for a self-reference: deleting one student would delete the chain of everyone below them. The set-based version keeps both statements in one transaction so no other request sees the half-done state: ```csharp await using var tx = await db.Database.BeginTransactionAsync(); await db.Students.Where(s => s.MentorId == id) .ExecuteUpdateAsync(u => u.SetProperty(s => s.MentorId, (int?)null)); await db.Students.Where(s => s.Id == id).ExecuteDeleteAsync(); await tx.CommitAsync(); ``` Neither call touches the change tracker, so any `Student` instances already tracked by this context still show the old `MentorId`. ## SQL Server's cycle rule SQL Server refuses a referential action when it could form cycles or multiple cascade paths, and a foreign key from `Students` to `Students` is a cycle. Creating the constraint fails with a message that it "may cause cycles or multiple cascade paths". The usual answer there is to keep `ClientSetNull` (or `ClientCascade` when deletion is wanted) and make sure EF Core sees the dependents, by loading them or by clearing the key first. ## Self-referencing many-to-many Course prerequisites are a self-referencing **many-to-many**: `Course.Prerequisites` and `Course.RequiredBy`. EF Core creates a join entity named `CourseCourse` with two foreign keys back to `Courses`, both cascading by default. Deleting a course then reaches the join table by two paths, which SQL Server also refuses; configure the two halves through `UsingEntity`'s left and right lambdas, giving one of them `OnDelete(DeleteBehavior.Restrict)` or `ClientCascade`, and remove those join rows in code. ## What interviewers listen for - That a nullable key changes only what EF Core does to **tracked** rows. - That the constraint's action is decided by `DeleteBehavior` and created by a migration. - That the provider matters: a model that migrates on PostgreSQL can fail on SQL Server. - That `Cascade` on a hierarchy is a business decision, not a fix: it removes every student below the deleted one. - That the failure surfaces as `DbUpdateException` from the database, not as an EF Core validation error, so it only appears when a mentor with unloaded mentees is deleted - a case worth an integration test against the real provider.

  • Why does SQL Server refuse OnDelete(DeleteBehavior.SetNull) on this relationship while PostgreSQL accepts it?
    SQL Server rejects any referential action that could form cycles or multiple cascade paths, and a foreign key from a table to itself is such a cycle, so creating the constraint fails. PostgreSQL has no such restriction. On SQL Server keep `ClientSetNull` and load the mentees, or null their key with a set-based update in the same transaction.
  • What if MentorId were a non-nullable int?
    The relationship would be required and default to `Cascade`, so deleting a mentor would delete the mentees, and on PostgreSQL the database would recurse down the whole chain. It is also a modelling problem: every student, the first one included, would need a mentor. A hierarchy with a root needs an optional key.

  • A nullable MentorId makes the database null the mentees' key automatically
  • ClientSetNull writes ON DELETE SET NULL into the migration
  • Switching to DeleteBehavior.Cascade is the safe fix for the failing delete
  • Querying the mentees with AsNoTracking lets EF Core clear their MentorId on save
  • EF Core needs a separate join table to map a self-referencing one-to-many