Tutorials Entity Framework Core Tutorial
Soft Delete Pattern in EF Core
Soft Delete Pattern in EF Core: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 25 of 100
Soft Delete Pattern in EF Core
Beginner ✓ → Intermediate → Advanced → Professional
Intermediate · 2 — Data & queries · ~6 min · Module 3: CRUD Operations
What is this?
Soft delete marks rows as deleted with a flag (IsDeleted, DeletedAt) instead of physical DELETE. HasQueryFilter automatically excludes them from normal queries.
Why should you care?
ShopNest must retain order and customer history for tax audits — soft delete hides catalog items while preserving referential integrity.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public bool IsDeleted { get; set; }
public DateTime? DeletedAt { get; set; }
}
// DbContext:
modelBuilder.Entity<Product>().HasQueryFilter(p => !p.IsDeleted);
// "Delete":
var p = await _context.Products.FindAsync(id);
p!.IsDeleted = true;
p.DeletedAt = DateTime.UtcNow;
await _context.SaveChangesAsync();
What happened?
- HasQueryFilter adds WHERE IsDeleted = 0 to every query on Product.
- Setting flags performs logical delete without breaking FK references from old orders.
Practice next
- Add IsDeleted and DeletedAt to Product.
- Configure HasQueryFilter and migrate.
- Soft-delete a product and confirm normal queries omit it.
- Add filtered unique index on Sku where IsDeleted = 0.
- build restore by clearing IsDeleted and DeletedAt.
Remember
Soft delete uses flags instead of DELETE. HasQueryFilter hides deleted rows globally. IgnoreQueryFilters bypasses filter intentionally.
ShopNest catalog retirement
Discontinued product soft-deleted but old OrderItems still reference it for invoice reprints.
Outcome: GST audit trail intact; storefront stops showing the listing.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!