📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show how you would implement soft delete in EF Core: a global query filter, an interceptor that turns deletes into updates, unique indexes that ignore deleted rows, what happens to cascades, and how you restore or permanently purge data.

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.

Mid-Level Coding Intermediate data-retention ef-core global-query-filters interceptors soft-delete sql-server

🎯 Key points

  • An ISoftDelete interface with IsDeleted and DeletedAt, and a named "SoftDelete" query filter (EF Core 10)
  • A SaveChangesInterceptor switches tracked Deleted entries to Modified and sets IsDeleted and DeletedAt, so callers keep using Remove()
  • ExecuteDelete, raw SQL and database cascades bypass the interceptor; for set-based soft deletes call ExecuteUpdate and set the flag yourself
  • EF Core cascades only to tracked dependents; database ON DELETE CASCADE never fires because no DELETE runs
  • Any unique index on a value a user may re-create (email, slug) needs HasFilter("[IsDeleted] = 0"); a restore can then still clash with a newer row and must handle the duplicate-key error
  • Required navigations to a filtered principal hide dependents through inner joins; EF Core warns, so give the dependent a matching filter or make the navigation optional
  • Restore with IgnoreQueryFilters(["SoftDelete"]), purge with a batched retention job using ExecuteDelete, and test both (interceptor, filter and index) against real SQL Server
  • Soft delete is not erasure: tables grow, every query pays the filter, and Privacy Act APP 11.2 still requires destroying data you no longer need

⏱ 30-second answer

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.

  • Unique indexes need HasFilter("[IsDeleted] = 0") or a deleted row blocks re-creating it.
  • Cascades apply only to tracked dependents; database cascades never fire.
  • 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I implement soft delete so that application code doesn't change: handlers still call Remove(), and the infrastructure turns it into an update. Entities implement ISoftDelete with IsDeleted and DeletedAt. A SaveChangesInterceptor looks for entries in the Deleted state, flips them to Modified, and sets the two columns. A global query filter, which in EF Core 10 I give a name like SoftDelete, hides those rows from every query. Restoring is IgnoreQueryFilters([\"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 no DELETE reaches SQL Server, ON DELETE CASCADE never 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. ExecuteDelete hard-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."


What changes when deletes become updates

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

Bypasses to know

API Goes through interceptor?
Remove() + SaveChanges Yes
ExecuteDelete() No: real DELETE (but the source query is filtered)
ExecuteSql("DELETE ...") No
SQL Server cascade No

Production example

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].

🔍 What the interviewer is checking

Checks that the candidate can implement soft delete transparently and knows its side effects on indexes, cascades, bypasses and data retention.

Green flags

  • Interceptor converts Deleted to Modified so callers keep using Remove()
  • Filtered unique index
  • Knows DB cascades do not fire and ExecuteDelete bypasses it
  • Mentions retention and purge

Red flags

  • Adding Where(x => !x.IsDeleted) by hand in every query
  • No answer for unique constraints or cascades
  • Calls soft delete a privacy-compliant deletion

📚 Learn in depth

1. The flow

handler: 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)

2. Cascades in detail

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:

  • load the children (Include) before removing,
  • soft-delete children with ExecuteUpdate in the same transaction,
  • or accept orphans that are hidden through the parent (risky with required navigations).

3. Filters and required navigations

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.

4. Indexes

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.

5. Restore and purge

  • Restore: query with IgnoreQueryFilters(["SoftDelete"]), clear the flag, save. Check uniqueness again: someone may have re-created the same email meanwhile.
  • Purge: a scheduled job with ExecuteDelete on rows where DeletedAt < now - retention, in batches.

6. Alternatives

  • Temporal tables: hard delete, but history keeps the old row; good for audit, less good for a user-facing "undo".
  • Archive table: move rows to Projects_Deleted; keeps the hot table small.
  • Status column: when "deleted" is really a business state (cancelled, archived), model it as such.

Try it yourself

  1. Implement the interceptor and confirm Remove() produces an UPDATE with EF Core logging.
  2. Delete a principal with and without loading its children, and compare the resulting rows.
  3. Create a unique index without a filter, soft-delete a user and try to re-create them.
  4. Call ExecuteDelete() and confirm it hard-deletes.
  5. Measure a list query on a table that is 50% soft-deleted, before and after a filtered index.

💻 Code

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);

⚠ Common mistakes

  • Mistake: Relying on 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.
  • Mistake: Keeping a plain unique index. Why it is wrong: A soft-deleted row blocks creating a new row with the same value. Instead: Use HasFilter("[IsDeleted] = 0").
  • Mistake: Assuming 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.
  • Mistake: Calling 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.
  • Mistake: Treating soft delete as erasure. Why it is wrong: The personal information is still stored, and APP 11.2 requires destroying or de-identifying data you no longer need. Instead: Add a retention-based purge.
  • Mistake: Soft-deleting everything by default. Why it is wrong: Every table grows and every query pays the filter cost. Instead: Use it where users need undo or history; use temporal tables for audit.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the global query filter Why: Checks filter internals and EF Core 10 named filters
    How to answer

    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.

  2. When: Candidate mentions ExecuteDelete or ExecuteUpdate Why: Checks what skipping the change tracker means for interceptors
    How to answer

    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.

  3. When: Candidate compares soft delete with keeping history Why: Checks when temporal tables fit better
    How to answer

    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.

🛠 Real-world problems: how you handle them

Re-registration failed after soft delete was introduced
Situation
[Membership platform on Azure SQL, ~2 million users]. Soft delete was added to `Users` with an interceptor and a global filter to support a 30-day account recovery window.
Signals
A spike of `DbUpdateException` with SQL error 2601 (duplicate key) on sign-up, support tickets from people who had closed their account and could not sign up again, and a rising sign-up failure metric in Application Insights.
Investigation
The exception named `IX_Users_Email`. Querying with `IgnoreQueryFilters()` showed the soft-deleted row still held the email. The migration had kept the original unfiltered unique index. A search also found an admin bulk action using `ExecuteDelete`, which hard-deleted users and skipped the recovery window.
Resolution
Immediate: a migration replacing the index with `HasIndex(u => u.Email).IsUnique().HasFilter("[IsDeleted] = 0")`, created online. Then changed the admin action to `ExecuteUpdate` setting the flag, and added a nightly purge job removing users soft-deleted more than 30 days ago.
Prevention
A model test that fails when an `ISoftDelete` entity has an unfiltered unique index, an analyser warning on `ExecuteDelete` for soft-delete entities outside the purge job, and a dashboard of purge counts.

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.

More in Production EF

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me