Soft delete in EF Core 10: ISoftDelete, a named query filter, a SaveChangesInterceptor converting Deleted to Modified, filtered unique indexes, cascade behaviour, restore and purge, and where it is bypassed.
Soft delete keeps the row and marks it deleted. In EF Core I add an ISoftDelete interface (IsDeleted, DeletedAt), a global query filter !e.IsDeleted (a named filter in EF Core 10), and a SaveChangesInterceptor that changes Deleted entries to Modified and sets the flag, so Remove() keeps working.
HasFilter("[IsDeleted] = 0") or a deleted row blocks re-creating it.ExecuteDelete and raw SQL bypass the interceptor.The trade-off: easy undo and history, against bigger tables, filter overhead on every query, and a purge job you still need for retention and privacy.
"I implement soft delete so that application code doesn't change: handlers still call
Remove(), and the infrastructure turns it into an update. Entities implementISoftDeletewithIsDeletedandDeletedAt. ASaveChangesInterceptorlooks for entries in theDeletedstate, flips them toModified, and sets the two columns. A global query filter, which in EF Core 10 I give a name likeSoftDelete, hides those rows from every query. Restoring isIgnoreQueryFilters([\"SoftDelete\"]), clear the flag, save.The details are where it goes wrong. A unique index on email now blocks a user from signing up again after deletion, so it becomes a filtered index on
IsDeleted = 0. Cascades change too: because noDELETEreaches SQL Server,ON DELETE CASCADEnever fires, and EF Core only cascades to dependents it is tracking. For example, at [company] deleting a project left [thousands of] visible tasks pointing at a hidden project, because the tasks weren't loaded. We fixed it by soft-deleting the children explicitly in the domain method and adding a test.The mistake I see is treating soft delete as free.
ExecuteDeletehard-deletes, raw SQL ignores the filter, every query pays for the extra predicate, and the table never shrinks. And soft-deleted personal information is still personal information under the Privacy Act, so you need a retention job that really deletes it. Soft delete is an undo feature, not a data-retention policy."
| Area | Hard delete | Soft delete |
|---|---|---|
| Queries | Row gone | Filter IsDeleted = 0 on every query |
| Unique constraints | Freed on delete | Need filtered unique index |
| DB cascades | ON DELETE CASCADE fires |
Never fires |
| EF cascades | Tracked dependents deleted | Tracked dependents marked Deleted → converted to soft delete |
| Table size | Shrinks | Grows until purged |
| Undo | Backup restore | Clear the flag |
| API | Goes through interceptor? |
|---|---|
Remove() + SaveChanges |
Yes |
ExecuteDelete() |
No: real DELETE (but the source query is filtered) |
ExecuteSql("DELETE ...") |
No |
| SQL Server cascade | No |
In a [document management system with 25 million rows, about 30% soft-deleted], adding the filter column to the main covering index and a nightly purge of rows deleted over [90 days] reduced the table by [7 million rows] and brought list queries back from [400 ms to 60 ms].
Checks that the candidate can implement soft delete transparently and knows its side effects on indexes, cascades, bypasses and data retention.
Green flags
Deleted to Modified so callers keep using Remove()ExecuteDelete bypasses itRed flags
Where(x => !x.IsDeleted) by hand in every queryhandler: db.Projects.Remove(project)
│ state = Deleted
▼
SaveChanges → SaveChangesInterceptor.SavingChanges
│ for each Deleted ISoftDelete: State = Modified, IsDeleted = true, DeletedAt = now
▼
UPDATE Projects SET IsDeleted = 1, DeletedAt = @p WHERE Id = @id
│
later: db.Projects.ToList() → WHERE IsDeleted = 0 (global filter)
When you call Remove(principal), EF Core applies its cascade rules to tracked dependents first (marking them Deleted for cascade, or nulling FKs for ClientSetNull). The interceptor then sees those dependents in Deleted state and converts them too, so tracked children are soft-deleted. Untracked children are untouched, and because only an UPDATE reaches SQL Server, the database's ON DELETE CASCADE does nothing. Options:
Include) before removing,ExecuteUpdate in the same transaction,If Task has a required navigation to Project, and Project is filtered, an Include(t => t.Project) uses an inner join and hides tasks of deleted projects, which may or may not be what you want. EF Core logs a warning for this model configuration. Give the dependent a matching filter or make the navigation optional.
CREATE UNIQUE INDEX IX_Users_Email ON Users (Email) WHERE IsDeleted = 0;
SQL Server's filtered indexes are used only when the query predicate matches the filter, and they require parameterisation awareness (IsDeleted = 0 is a literal from the filter, so it matches). For hot tables where most rows are live, putting IsDeleted in the main indexes, or a filtered nonclustered index on live rows, keeps the extra predicate cheap.
IgnoreQueryFilters(["SoftDelete"]), clear the flag, save. Check uniqueness again: someone may have re-created the same email meanwhile.ExecuteDelete on rows where DeletedAt < now - retention, in batches.Projects_Deleted; keeps the hot table small.Remove() produces an UPDATE with EF Core logging.ExecuteDelete() and confirm it hard-deletes.Soft delete with a named filter, an interceptor and a filtered unique index:
namespace Docs.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
public interface ISoftDelete
{
bool IsDeleted { get; set; }
DateTimeOffset? DeletedAt { get; set; }
}
public sealed class Folder : ISoftDelete
{
public int Id { get; init; }
public required string Name { get; set; }
public required string Slug { get; set; }
public List<Document> Documents { get; } = [];
public bool IsDeleted { get; set; }
public DateTimeOffset? DeletedAt { get; set; }
}
public sealed class Document : ISoftDelete
{
public int Id { get; init; }
public int FolderId { get; set; }
public required string Title { get; set; }
public bool IsDeleted { get; set; }
public DateTimeOffset? DeletedAt { get; set; }
}
public sealed class SoftDeleteInterceptor(TimeProvider clock) : SaveChangesInterceptor
{
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken ct = default)
{
foreach (var entry in eventData.Context!.ChangeTracker.Entries<ISoftDelete>())
{
if (entry.State != EntityState.Deleted) continue;
// Turn the DELETE into an UPDATE so the row (and its history) is kept.
entry.State = EntityState.Modified;
entry.Entity.IsDeleted = true;
entry.Entity.DeletedAt = clock.GetUtcNow();
}
return base.SavingChangesAsync(eventData, result, ct);
}
}
public sealed class DocsDbContext(DbContextOptions<DocsDbContext> options) : DbContext(options)
{
public DbSet<Folder> Folders => Set<Folder>();
public DbSet<Document> Documents => Set<Document>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Folder>(b =>
{
b.HasQueryFilter("SoftDelete", f => !f.IsDeleted);
// Deleted rows must not block re-creating the same slug.
b.HasIndex(f => f.Slug).IsUnique().HasFilter("[IsDeleted] = 0");
});
// Matching filter on the dependent avoids the required-navigation warning.
modelBuilder.Entity<Document>().HasQueryFilter("SoftDelete", d => !d.IsDeleted);
}
}
Deleting with children, restoring, and purging:
namespace Docs.Application;
using Docs.Infrastructure;
using Microsoft.EntityFrameworkCore;
public sealed class FolderService(DocsDbContext db, TimeProvider clock)
{
public async Task DeleteAsync(int id, CancellationToken ct)
{
// Load children so EF Core cascades to them and the interceptor soft-deletes them too.
var folder = await db.Folders.Include(f => f.Documents).SingleAsync(f => f.Id == id, ct);
db.Folders.Remove(folder);
await db.SaveChangesAsync(ct);
}
public async Task RestoreAsync(int id, CancellationToken ct)
{
var folder = await db.Folders.IgnoreQueryFilters(["SoftDelete"])
.SingleAsync(f => f.Id == id, ct);
folder.IsDeleted = false;
folder.DeletedAt = null;
await db.SaveChangesAsync(ct); // the filtered unique index rejects a clash with a newer folder
}
public Task<int> PurgeAsync(TimeSpan retention, CancellationToken ct)
{
var cutoff = clock.GetUtcNow() - retention;
// ExecuteDelete is a real DELETE and bypasses the interceptor: exactly what a purge needs.
return db.Folders.IgnoreQueryFilters(["SoftDelete"])
.Where(f => f.IsDeleted && f.DeletedAt < cutoff)
.ExecuteDeleteAsync(ct);
}
}
-- Remove(folder) with the interceptor:
UPDATE [Folders] SET [DeletedAt] = @p0, [IsDeleted] = @p1 WHERE [Id] = @p2;
-- Normal query:
SELECT ... FROM [Folders] AS [f] WHERE [f].[IsDeleted] = CAST(0 AS bit);
ON DELETE CASCADE for children. Why it is wrong: No DELETE is sent, so the database cascade never runs. Instead: Load and remove children, or soft-delete them with ExecuteUpdate in the same transaction.HasFilter("[IsDeleted] = 0").ExecuteDelete respects soft delete. Why it is wrong: It sends a real DELETE and skips interceptors. Instead: Use ExecuteUpdate to set the flag, and keep ExecuteDelete for purges.IgnoreQueryFilters() with no names to show deleted items. Why it is wrong: It also removes the tenant filter. Instead: Use EF Core 10 named filters and ignore only SoftDelete.Soft delete is a product decision as much as a technical one. Before adding it I ask who needs to see deleted data, for how long, and why. If the answer is "auditors", temporal tables are usually better. If it is "users want an undo for 30 days", soft delete plus a 30-day purge is right. If it is "just in case", that is usually a privacy liability.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Soft delete flag + filter | User-facing undo, recycle bin | Larger tables, filter cost, purge job | Pure audit needs |
| Temporal tables | Audit, point-in-time reads | History storage | User-facing undo lists |
| Archive table | Large tables, rare restores | Move logic | Frequent restores |
| Hard delete | Data with no recovery need | Restore from backup only | Regulated records |
A global query filter is a predicate configured with HasQueryFilter that EF Core adds to every LINQ query for that entity type: direct queries, Includes, navigation loads, Find and even ExecuteUpdate/ExecuteDelete. Typical uses are soft delete (!IsDeleted) and multi-tenancy (TenantId == _tenantId). Per-request values must come from a DbContext member so EF parameterises them per context instance. IgnoreQueryFilters() turns filters off for one query, and EF Core 10 named filters let you define several and ignore just one (IgnoreQueryFilters(["SoftDelete"])). The big pitfall: a required navigation to a filtered entity becomes an INNER JOIN, so dependants vanish silently. The trade-off is safety by default versus hidden behaviour that surprises people and needs matching indexes.
For set-based changes use ExecuteUpdateAsync/ExecuteDeleteAsync (EF Core 7+): one UPDATE/DELETE statement, no entities loaded, and in EF Core 10 the setters can be a normal lambda. For inserts, AddRange + SaveChanges already batches commands (default 42 statements per batch on SQL Server) with MERGE ... OUTPUT for keys, which is fine up to tens of thousands of rows. Beyond that, SqlBulkCopy streams rows with the bulk-load protocol and is an order of magnitude faster; for upserts use a staging table + MERGE or a table-valued parameter. Third-party libraries wrap these, but check their licences. Skipping the change tracker has costs: tracked entities go stale, SaveChanges interceptors (audit, soft delete) don't run, and concurrency tokens aren't checked. The trade-off is raw speed versus the safety nets EF normally gives you.
A system-versioned temporal table makes SQL Server copy the previous version of a row into a history table on every UPDATE and DELETE, stamping period columns (PeriodStart/PeriodEnd, UTC). Since EF Core 6 you configure it with ToTable(t => t.IsTemporal()); the period columns become shadow properties and migrations create the history table. You query history with TemporalAsOf(utc), TemporalAll(), TemporalFromTo, TemporalBetween and TemporalContainedIn, which return untracked results; restoring a deleted row is a TemporalAsOf query followed by Add. Temporal tables record what and when, not who, so you still need a ModifiedBy column. The trade-off: point-in-time history for free in code, paid for in history storage that grows with every update and needs a retention policy.
How to tell it (STAR)
**S:** At [company] we added soft delete to user accounts to support a [30-day] recovery window. **T:** Within [a day], sign-ups started failing for returning users and I was asked to fix it. **A:** The duplicate key error pointed to the email unique index, which still counted deleted rows. I replaced it with a filtered index, found an admin action that hard-deleted with `ExecuteDelete` and changed it to a soft delete, and added a purge job for the retention window plus a model test for unfiltered unique indexes. **R:** Sign-up failures dropped to [zero] the same day, and the purge job removes [about N] expired accounts a night, keeping us within our privacy policy.
Last updated 23 Nov 2026.