liveBook · Manning

Cascading delete

As explained in .NET in Action, Second Edition

Cascade delete is a relational-data behavior in which deleting a principal record also deletes its related dependent records.

Cascading delete removes dependent records when their principal record is deleted. In an Entity Framework Core API, deleting a Book can therefore remove its related Ratings. section 5.5

EF Core assumes this relationship should cascade, but a simple entity lookup may not translate the dependent deletion into SQL. The database then rejects the delete because Ratings still reference the Book through foreign keys. section 5.5

Make the dependent relationship available before removing the principal:

  • Load the Book together with its Ratings. section 5.5
  • Remove the Book and call SaveChangesAsync. section 5.5
  • Return an appropriate HTTP response, such as 404 when the Book does not exist and 204 after deletion. section 5.5

Load dependents before deletion

var book = await _dbContext.Books .Include(b => b.Ratings) .FirstOrDefaultAsync(b => b.Id == id, cancellationToken); section 5.5

How .NET in Action, Second Edition covers it

How deep it goes
Explains runtime failure and fixes it by eagerly loading dependent entities before deletion.
Examples
Uses a Book with related Ratings and an HTTP DELETE endpoint as the implementation example.
What it assumes
Assumes familiarity with Entity Framework Core entities, relationships, asynchronous queries, and HTTP controller actions.
What you can do after
Diagnose and apply cascade deletion by loading related entities with Include before calling SaveChangesAsync.
How it connects
Connects relational databases, foreign keys, Entity Framework Core, principal entities, and dependent entities.

Also explained in

Compare how 3 books explain cascading delete →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.