惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Apple Machine Learning Research
Apple Machine Learning Research
Last Week in AI
Last Week in AI
Blog — PlanetScale
Blog — PlanetScale
V
Visual Studio Blog
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
博客园 - Franky
IT之家
IT之家
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
The GitHub Blog
The GitHub Blog
雷峰网
雷峰网
腾讯CDC
博客园 - 聂微东
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
人人都是产品经理
人人都是产品经理
MongoDB | Blog
MongoDB | Blog
大猫的无限游戏
大猫的无限游戏
Martin Fowler
Martin Fowler
宝玉的分享
宝玉的分享
博客园_首页
G
Google Developers Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Implementing Soft Delete with Filtered Indexes in Entity ...
ZèD · 2026-04-23 · via DEV Community

ZèD

Soft Delete with Global Query Filters and Filtered Indexes in Entity Framework Core

Soft delete sounds simple until it reaches production.

If you only add an IsDeleted flag, you have not finished the job. You still need:

  • Default queries that hide deleted rows
  • A write path that converts deletes into updates
  • Unique constraints that ignore soft-deleted rows
  • A restore path that does not break the model

This article shows a clean EF Core pattern that keeps the implementation explicit and maintainable.

The Core Idea

Soft delete is a domain concern, not just a database trick. The model should express that an entity can be deleted and restored.

An interface keeps the contract small and avoids forcing every entity into the same inheritance tree:

public interface ISoftDeletable
{
    bool IsDeleted { get; }
    DateTimeOffset? DeletedAt { get; }

    void Delete();
    void Restore();
}

Enter fullscreen mode Exit fullscreen mode

A simple base entity can implement the behavior:

public abstract class BaseEntity : ISoftDeletable
{
    public Guid Id { get; private set; } = Guid.NewGuid();
    public bool IsDeleted { get; private set; }
    public DateTimeOffset? DeletedAt { get; private set; }

    public void Delete()
    {
        if (IsDeleted)
        {
            return;
        }

        IsDeleted = true;
        DeletedAt = DateTimeOffset.UtcNow;
    }

    public void Restore()
    {
        if (!IsDeleted)
        {
            return;
        }

        IsDeleted = false;
        DeletedAt = null;
    }
}

Enter fullscreen mode Exit fullscreen mode

That gives the application one place to define the lifecycle of a deleted record.

Turn Deletes Into Updates

The easiest way to preserve EF Core's normal API is to intercept Deleted entities before they hit the database.

For most applications, a SaveChanges override is enough:

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    private void ApplySoftDelete()
    {
        foreach (var entry in ChangeTracker.Entries<ISoftDeletable>()
                     .Where(e => e.State == EntityState.Deleted))
        {
            entry.State = EntityState.Modified;
            entry.Entity.Delete();
        }
    }

    public override int SaveChanges()
    {
        ApplySoftDelete();
        return base.SaveChanges();
    }

    public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
    {
        ApplySoftDelete();
        return base.SaveChangesAsync(cancellationToken);
    }
}

Enter fullscreen mode Exit fullscreen mode

This keeps your service layer clean:

context.Users.Remove(user);
await context.SaveChangesAsync();

Enter fullscreen mode Exit fullscreen mode

From the caller's perspective, it is still a delete. Internally, the row is retained and marked as deleted.

If your project already uses EF Core interceptors for auditing or multi-tenant behavior, you can move this logic there instead. The important part is consistency, not the specific hook.

Filter Rows By Default

Global query filters ensure deleted rows stay out of normal reads:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
        .HasQueryFilter(u => !u.IsDeleted);

    base.OnModelCreating(modelBuilder);
}

Enter fullscreen mode Exit fullscreen mode

That gives you the default behavior you want without repeating Where(u => !u.IsDeleted) everywhere.

When you intentionally need deleted rows, use IgnoreQueryFilters():

var deletedUser = await context.Users
    .IgnoreQueryFilters()
    .FirstOrDefaultAsync(u => u.Id == userId && u.IsDeleted);

Enter fullscreen mode Exit fullscreen mode

That is the right escape hatch for restore flows, admin views, and audits.

Protect Unique Constraints

This is where many soft-delete implementations break down.

If Email is unique, then a deleted user should not block another user from using the same email later. A filtered index solves that.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
        .HasQueryFilter(u => !u.IsDeleted);

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

    base.OnModelCreating(modelBuilder);
}

Enter fullscreen mode Exit fullscreen mode

That example is SQL Server syntax. Other providers use different SQL for filtered or partial indexes, so the exact filter expression is provider-specific.

The architectural point is more important than the syntax:

  • Filter unique indexes on active rows only
  • Do not rely on IsDeleted alone to preserve uniqueness
  • Verify the generated migration for your provider

Restore Safely

Restoring a row should be a first-class operation, not a manual flag flip hidden in business code.

var user = await context.Users
    .IgnoreQueryFilters()
    .FirstOrDefaultAsync(u => u.Id == userId);

if (user is null)
{
    return;
}

user.Restore();
await context.SaveChangesAsync();

Enter fullscreen mode Exit fullscreen mode

This works because the model already knows how deletion and restoration behave.

Design Notes

  • Prefer a global query filter over ad hoc Where clauses. It is harder to forget and easier to reason about.
  • Use filtered or partial indexes for business keys that must remain unique among active rows.
  • Do not add an index on IsDeleted by default. The column is usually low-selectivity and rarely useful on its own.
  • Test Include queries and required relationships. Global filters apply everywhere, and that can affect query shape.
  • If you use bulk operations such as ExecuteDelete, remember they bypass the change tracker and will not trigger your soft-delete pipeline.

When This Pattern Fits

This approach works well when you need:

  • Auditability
  • Recovery from accidental deletes
  • Safer admin tooling
  • Stable referential history

It is less useful when data must be physically removed for legal, privacy, or retention reasons. In those cases, hard delete is the correct answer.

Conclusion

Soft delete is a small feature that becomes a large architectural problem if you treat it as a single boolean column.

The production-ready version has three parts:

  1. Convert deletes into updates
  2. Filter deleted rows out of normal queries
  3. Make unique constraints ignore deleted rows

Once those are in place, the rest of the application can use EF Core naturally without repeating soft-delete rules everywhere.

References