Skip to content

Soft Deletes in EF Core — Global Query Filters Explained

Build soft delete in EF Core 10 with global query filters, a SaveChangesInterceptor, named tenant filters, and a restore path. Learn the production traps: bulk deletes, cascading, required relationships, unique indexes, and retention.

Isaiah Clifford Opoku
Isaiah Clifford OpokuSoftware Engineer & ArchitectNovember 17, 2026·16 min read

A user deletes an order by accident and asks support to bring it back. An auditor wants to know who removed a customer record last March. A report suddenly shows different totals for last year because someone deleted an old product. With a normal DELETE, the row is gone from the live table. Recovery now depends on backups or a separate history system.

Soft delete takes a different approach. Instead of removing the row, you mark it as deleted and hide it from normal queries. EF Core makes the hiding practical with global query filters, and EF Core 10 improves the approach with named filters.

But soft delete has more sharp edges than most tutorials admit: ExecuteDelete still hard-deletes, unique indexes can block reuse, related data needs an explicit policy, and required relationships can change query results. This post covers the basic setup, automatic filter registration, named filters, restoration, and the problems to handle before production.

The examples target EF Core 10 with SQL Server, unless stated otherwise. Named filters require EF Core 10. ICurrentUser and ITenantProvider below are application services you supply.

Hard delete vs soft delete

-- Hard delete: the row is gone from the live table
DELETE FROM Orders WHERE Id = 42;

-- Soft delete: the row stays, marked as deleted
UPDATE Orders
SET IsDeleted = 1, DeletedAtUtc = SYSUTCDATETIME()
WHERE Id = 42;

Every query that should ignore deleted rows needs WHERE IsDeleted = 0. One missed condition and deleted orders can show up in a customer’s order history. Global query filters put that default in your EF model instead of repeating it throughout the application.

flowchart TD
    A[Application calls Remove on an order] --> B[SaveChanges runs the interceptor]
    B --> C[Change Deleted state to an update]
    C --> D[Set IsDeleted and deletion metadata]
    D --> E[Database keeps the row]
    E --> F[Normal EF query applies the soft delete filter]
    F --> G[Deleted order stays out of the results]

The interceptor changes writes. The query filter changes reads. You need both for Remove() to behave like a soft delete.

Step 1: mark entities as soft-deletable

Use an interface so the interceptor and model configuration can identify eligible entities:

public interface ISoftDeletable
{
    bool IsDeleted { get; set; }
    DateTime? DeletedAtUtc { get; set; }
    string? DeletedBy { get; set; }
}

public class Order : ISoftDeletable
{
    public int Id { get; set; }
    public int CustomerId { get; set; }
    public Guid TenantId { get; set; }
    public decimal Total { get; set; }
    public List<OrderLine> Lines { get; set; } = new();

    public bool IsDeleted { get; set; }
    public DateTime? DeletedAtUtc { get; set; }
    public string? DeletedBy { get; set; }
}

IsDeleted drives the filter. DeletedAtUtc and DeletedBy answer when and by whom the row was most recently deleted. Prefer a stable user identifier to a display name if your identity system provides one.

These fields are not a complete audit log: restoring a record clears them in the example below, and a later deletion replaces them. If you need a permanent history of who did what, write audit events separately.

Step 2: add a global query filter

A global query filter is a predicate that EF Core adds when it queries an entity type:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Order>().HasQueryFilter(o => !o.IsDeleted);
}

Now this:

var orders = await db.Orders
    .Where(o => o.CustomerId == customerId)
    .ToListAsync();

produces SQL shaped like this:

SELECT [o].[Id], [o].[CustomerId], [o].[Total], ...
FROM [Orders] AS [o]
WHERE [o].[IsDeleted] = CAST(0 AS bit)
  AND [o].[CustomerId] = @customerId;

The predicate also participates in queries using Include, navigation expansion, Count, Any, and projections. It is a default for database queries, not an authorization boundary or an in-memory collection filter. Already tracked entities and navigation fixup can produce surprises in a long-lived context; use a fresh, short-lived context for recycle-bin operations.

Add and apply a migration for the new columns and indexes before using the feature:

dotnet ef migrations add AddSoftDelete
dotnet ef database update

On existing tables, check the migration gives existing rows IsDeleted = false. Review the generated migration before applying it to production.

Step 3: turn deletes into updates automatically

The filter hides deleted rows, but db.Orders.Remove(order) still schedules a real DELETE. A SaveChangesInterceptor can turn tracked deletions into updates.

Handle both synchronous and asynchronous saves so a different calling style cannot accidentally bypass the policy:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

public interface ICurrentUser
{
    string? UserId { get; }
}

public sealed class SoftDeleteInterceptor : SaveChangesInterceptor
{
    private readonly ICurrentUser _currentUser;

    public SoftDeleteInterceptor(ICurrentUser currentUser)
        => _currentUser = currentUser;

    private void ApplySoftDeletes(DbContext? context)
    {
        if (context is null)
            return;

        context.ChangeTracker.DetectChanges();
        var deletedAt = DateTime.UtcNow;
        var deletedBy = _currentUser.UserId;
        var entries = context.ChangeTracker.Entries<ISoftDeletable>()
            .Where(e => e.State == EntityState.Deleted)
            .ToList();

        foreach (var entry in entries)
        {
            // Cancel the deletion without marking every column modified.
            entry.State = EntityState.Unchanged;
            entry.Property(e => e.IsDeleted).CurrentValue = true;
            entry.Property(e => e.IsDeleted).IsModified = true;
            entry.Property(e => e.DeletedAtUtc).CurrentValue = deletedAt;
            entry.Property(e => e.DeletedAtUtc).IsModified = true;
            entry.Property(e => e.DeletedBy).CurrentValue = deletedBy;
            entry.Property(e => e.DeletedBy).IsModified = true;
        }
    }

    public override InterceptionResult<int> SavingChanges(
        DbContextEventData eventData, InterceptionResult<int> result)
    {
        ApplySoftDeletes(eventData.Context);
        return result;
    }

    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData eventData,
        InterceptionResult<int> result,
        CancellationToken cancellationToken = default)
    {
        ApplySoftDeletes(eventData.Context);
        return ValueTask.FromResult(result);
    }
}

Setting the whole entry to Modified is shorter, but marks all updateable properties for writing. Here only the deletion fields are updated. Any other pending edits on an entity being deleted are deliberately discarded; decide whether that matches your domain.

Register your current-user service and the interceptor as scoped services. The example assumes ICurrentUser is already registered:

builder.Services.AddScoped<SoftDeleteInterceptor>();

builder.Services.AddDbContext<AppDbContext>((sp, options) =>
    options.UseSqlServer(connectionString)
        .AddInterceptors(sp.GetRequiredService<SoftDeleteInterceptor>()));

Application code still calls Remove():

var order = await db.Orders.SingleOrDefaultAsync(o => o.Id == id, ct)
    ?? throw new InvalidOperationException($"Order {id} not found.");

db.Orders.Remove(order);
await db.SaveChangesAsync(ct);
// UPDATE Orders SET IsDeleted = 1, DeletedAtUtc = ..., DeletedBy = ...

This handles ordinary tracked entities. Owned entities, table splitting, and cascade-delete relationships need separate design and testing; an interceptor is not a universal substitute for an aggregate deletion policy.

Step 4: apply the filter to every soft-deletable entity

Writing the same filter for each entity is repetitive. Register a named filter for every eligible root entity after your other entity configurations:

using System.Reflection;

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);

    var roots = modelBuilder.Model.GetEntityTypes()
        .Where(t => typeof(ISoftDeletable).IsAssignableFrom(t.ClrType)
            && t.BaseType is null
            && !t.IsOwned())
        .ToList();

    foreach (var entityType in roots)
    {
        typeof(AppDbContext)
            .GetMethod(nameof(ApplySoftDeleteFilter),
                BindingFlags.NonPublic | BindingFlags.Static)!
            .MakeGenericMethod(entityType.ClrType)
            .Invoke(null, new object[] { modelBuilder });
    }
}

private static void ApplySoftDeleteFilter<TEntity>(ModelBuilder modelBuilder)
    where TEntity : class, ISoftDeletable
{
    modelBuilder.Entity<TEntity>()
        .HasQueryFilter("SoftDelete", e => !e.IsDeleted);
}

The generic helper keeps the predicate readable instead of constructing an expression tree by hand. Filters can only be configured on the root of an inheritance hierarchy, and derived entities inherit them. Put the interface on that root. Owned types are excluded here because they cannot have their own independent query filter; handle them through their owner.

This is an EF Core 10 helper because it uses the name "SoftDelete". On older versions, combine all predicates into one HasQueryFilter expression instead.

EF Core 10: named query filters

Before EF Core 10, each entity type could have only one query filter. Calling HasQueryFilter twice replaced the first expression:

// The second unnamed filter replaces the first.
modelBuilder.Entity<Order>().HasQueryFilter(o => !o.IsDeleted);
modelBuilder.Entity<Order>().HasQueryFilter(o => o.TenantId == _tenantId);

The workaround was o => !o.IsDeleted && o.TenantId == _tenantId. But then IgnoreQueryFilters() disabled both conditions. A recycle bin that forgot to add the tenant condition back could expose other tenants’ records.

EF Core 10 named filters let you configure and disable predicates separately:

public interface ITenantProvider
{
    Guid CurrentTenantId { get; }
}

public class AppDbContext : DbContext
{
    private readonly Guid _tenantId;

    public AppDbContext(
        DbContextOptions<AppDbContext> options, ITenantProvider tenants)
        : base(options) => _tenantId = tenants.CurrentTenantId;

    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Order>()
            .HasQueryFilter("SoftDelete", o => !o.IsDeleted)
            .HasQueryFilter("Tenant", o => o.TenantId == _tenantId);
    }
}

This is the explicit configuration alternative to the automatic soft-delete helper. If using that helper, configure "Tenant" in your entity setup and let the helper add "SoftDelete".

flowchart TD
    A[Query Orders] --> B{Which operation?}
    B -->|Normal list| C[SoftDelete and Tenant filters enabled]
    C --> D[Live orders for the current tenant]
    B -->|Recycle bin| E[Disable only SoftDelete]
    E --> F[Tenant filter remains enabled]
    F --> G[Add IsDeleted condition]
    G --> H[Deleted orders for the current tenant]

The recycle-bin query is:

var deletedOrders = await db.Orders
    .IgnoreQueryFilters(["SoftDelete"])
    .Where(o => o.IsDeleted)
    .ToListAsync(ct);

Calling IgnoreQueryFilters() without arguments still disables all filters. Keep recycle-bin and restore endpoints authorized, and treat global filters as one layer of tenant isolation, not your entire security model.

Reference tenant state through a member of the DbContext instance, as _tenantId does above. EF caches the model, but can parameterize context members for each instance. Capturing a model-building local can bake the first value into the cached model. If you pool contexts, you also need an explicit strategy to initialize and reset tenant state for every lease.

Restoring deleted data

Undeleting is an update on a row you intentionally make visible:

public async Task RestoreOrderAsync(int id, CancellationToken ct)
{
    var order = await db.Orders
        .IgnoreQueryFilters(["SoftDelete"])
        .SingleOrDefaultAsync(o => o.Id == id && o.IsDeleted, ct)
        ?? throw new InvalidOperationException($"Deleted order {id} not found.");

    order.IsDeleted = false;
    order.DeletedAtUtc = null;
    order.DeletedBy = null;

    await db.SaveChangesAsync(ct);
}

The tenant predicate stays enabled. The caller must still have permission to restore that order. Restoration can fail if another live row has claimed a unique value, so handle that conflict explicitly.

stateDiagram-v2
    [*] --> Active
    Active --> SoftDeleted: Remove and SaveChanges
    SoftDeleted --> Active: Authorized restore
    SoftDeleted --> Purged: Retention policy and deliberate hard delete
    Purged --> [*]

Restoring a parent does not automatically restore children. If you cascade soft deletes, record enough information to distinguish children deleted with the parent from children deleted independently.

The gotchas

1. ExecuteDelete is a hard delete

ExecuteDeleteAsync sends SQL straight to the database without SaveChanges, so the interceptor never runs:

// Permanently deletes matching live rows.
await db.Orders
    .Where(o => o.CustomerId == customerId)
    .ExecuteDeleteAsync(ct);

The query filters still restrict which rows match. They do not turn the SQL DELETE into an update. For a bulk soft delete, use ExecuteUpdateAsync and set all deletion fields yourself:

var deletedAt = DateTime.UtcNow;
var deletedBy = currentUser.UserId;

await db.Orders
    .Where(o => o.CustomerId == customerId)
    .ExecuteUpdateAsync(setters => setters
        .SetProperty(o => o.IsDeleted, true)
        .SetProperty(o => o.DeletedAtUtc, deletedAt)
        .SetProperty(o => o.DeletedBy, deletedBy), ct);

Bulk operations execute immediately and do not synchronize already tracked entities. Use a separate context or deliberately reload affected state. Multiple bulk statements are not automatically one transaction; wrap parent and child updates in an explicit transaction if they must succeed together. Also check affected row counts when enforcing concurrency rules.

Reserve ExecuteDelete on these entities for deliberate permanent purges. Raw SQL writes bypass the interceptor too.

2. Soft delete doesn’t provide a cascade policy

A database ON DELETE CASCADE runs on a real delete. Updating the parent’s IsDeleted flag does not activate it. Unloaded children therefore stay unchanged unless your application updates them.

There is a second trap: EF’s change tracker can already have marked loaded dependents as Deleted when you removed the parent. The interceptor converts dependents implementing ISoftDeletable, but other dependents may still be hard-deleted. Inspect relationship delete behaviors and test with both loaded and unloaded children.

Choose a policy for each aggregate:

  • Keep child rows and ensure every relevant query respects the parent’s visibility.
  • Soft-delete children explicitly, including unloaded ones through a dedicated operation.
  • Hard-delete children deliberately if they have no restoration or retention requirements.

A domain method that loops over order.Lines only handles the lines that are actually loaded. For reliable bulk cascading, update children and parent in a transaction, with explicit tenant predicates or appropriate filters on every entity being updated.

Hiding an order also doesn’t guarantee stable historical reports. Reports must define whether deleted records count, and old order lines often need price and product-name snapshots rather than depending on the current product row.

3. Required relationships and filters can change results

Suppose Order has a filter and OrderLine does not. Each line requires an order:

var lines = await db.OrderLines.Include(l => l.Order).ToListAsync(ct);

EF can use an INNER JOIN for that required navigation. Filtering the order out also removes its lines from this query, even though querying OrderLines alone may return them. EF warns about this configuration during model validation.

Make the visibility rules consistent. If a line should be hidden whenever its order is hidden, a matching dependent filter can express that:

modelBuilder.Entity<OrderLine>()
    .HasQueryFilter("SoftDelete", l => !l.IsDeleted && !l.Order.IsDeleted);

This assumes OrderLine has its own flag and a required Order navigation. In a multi-tenant model, give dependents the appropriate tenant filter too. Avoid cycles in navigation-based filters.

Simply adding an independent !l.IsDeleted filter is insufficient if the parent is marked deleted but the line is not. Alternatively, make the relationship optional if that reflects the domain and your code handles a missing visible parent.

4. Unique indexes can block reuse and restoration

A unique index on Users.Email still sees a soft-deleted row. A new signup with the same email can fail. On SQL Server, enforce uniqueness only among live rows:

modelBuilder.Entity<User>()
    .HasIndex(u => u.Email)
    .IsUnique()
    .HasFilter("[IsDeleted] = 0");

PostgreSQL supports partial indexes with a provider-specific predicate such as .HasFilter("\"IsDeleted\" = false"). In a multi-tenant app, decide whether the unique key should include TenantId as well.

The tradeoff is restoration: if a new account reuses the email, restoring the old account violates the unique index. Your restore workflow needs a clear conflict policy.

5. Review indexes against real query plans

Every normal query now includes a soft-delete condition. On SQL Server, a filtered index can be useful:

modelBuilder.Entity<Order>()
    .HasIndex(o => new { o.TenantId, o.CustomerId })
    .HasFilter("[IsDeleted] = 0");

This index contains live rows and follows a common tenant-and-customer lookup. The right key order and predicate depend on your workload and provider. Check generated SQL and actual execution plans; an index on a low-selectivity Boolean column alone is rarely the whole answer.

If deleted rows accumulate, choose an archive or purge policy based on retention needs. Moving records to an archive affects foreign keys, restoration, and reports, so design it as a separate workflow.

6. Soft delete still retains personal data

An IsDeleted = true flag does not erase personal data. If a deletion request or retention policy requires erasure, plan a deliberate purge or suitable anonymization. The right policy depends on the data and applicable requirements; a 30-day window is an example, not a universal rule.

// Example policy: purge this tenant's users after a 30-day retention window.
var cutoff = DateTime.UtcNow.AddDays(-30);

await db.Users
    .IgnoreQueryFilters(["SoftDelete"])
    .Where(u => u.IsDeleted && u.DeletedAtUtc < cutoff)
    .ExecuteDeleteAsync(ct);

Only "SoftDelete" is disabled here, so a configured "Tenant" filter remains active. A cross-tenant maintenance job needs an explicitly authorized scope. Account for dependent records, backups, logs, and audit requirements as part of the retention design.

7. Filters don’t cover every access path

Filters apply to EF entity queries. Other access paths need separate treatment:

  • ExecuteSql and raw database commands execute the SQL you supply; EF does not add predicates.
  • Composable FromSql entity queries can have query filters applied on top. That does not make arbitrary SQL, stored procedure calls, or unmapped Database.SqlQuery<T> results automatically safe.
  • Reporting tools, direct SQL clients, and other applications do not inherit your EF model’s filters.

A database view such as ActiveOrders can make the intended default clearer for external readers. If tenant isolation must hold outside EF too, consider database-enforced controls rather than relying on application query filters alone.

When to use soft delete, and when not to

Soft delete is a good fit when users need an undo or recycle bin, records must remain accessible for an approved retention purpose, or physical deletion would break references you need to preserve.

Consider alternatives when:

  • You need every version of a row. SQL Server temporal tables provide row-version history and EF temporal queries. They do not automatically record the application user responsible for a change.
  • You need a durable audit trail. Record immutable audit events separately; three deletion fields cannot describe a record’s complete lifecycle.
  • The data requires actual erasure. Use a defined purge or anonymization workflow.
  • Deleted rows would vastly outnumber live ones. Temporary sessions and short-lived records may be better suited to expiry and hard deletion.
  • Deletion is really a business state. A cancelled order or deactivated account often deserves an explicit Status and domain rules rather than a hidden technical flag.

For context on where this persistence behavior belongs, see the earlier Repository and Unit of Work discussion. For scheduled cleanup, the hosted services guide covers background execution and its reliability limits.

Checklist

  • Add IsDeleted, DeletedAtUtc, and DeletedBy, and apply the reviewed migration.
  • Configure the soft-delete filter on eligible root entities; handle owned types separately.
  • Use EF Core 10 named filters to keep tenant filtering enabled during restoration.
  • Intercept both sync and async saves, and update only the intended deletion fields.
  • Read tenant state from the current context; review context pooling if used.
  • Reserve ExecuteDelete for deliberate purges; set metadata explicitly in bulk updates.
  • Test parent deletion with both loaded and unloaded dependents.
  • Keep required-navigation visibility rules consistent.
  • Review unique indexes and define restore-conflict behavior.
  • Validate important query plans against the real database provider.
  • Authorize recycle-bin and restore operations, and test cross-tenant isolation.
  • Define retention, purge, and audit policies separately.

Test these behaviors with the real relational provider: query translation, filtered indexes, joins, cascade rules, and bulk commands are exactly the things an in-memory fake cannot establish for you.

Conclusion

Soft delete keeps a row available for recovery while global query filters hide it from ordinary EF queries. A SaveChangesInterceptor makes tracked Remove() calls follow that policy, and EF Core 10’s named filters let a recycle bin reveal deleted records while retaining the tenant predicate.

Reliability comes from handling the boundaries: bulk commands bypass the interceptor, loaded and unloaded dependents behave differently, required joins can hide additional rows, unique values may be reused, and retained personal data eventually needs an appropriate erasure policy. Make those decisions explicit and soft delete becomes a useful recovery mechanism instead of a collection of surprises.

Further reading

Found this useful? Share it

XLinkedIn

Discussion