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

推荐订阅源

Vercel News
Vercel News
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
aimingoo的专栏
aimingoo的专栏
WordPress大学
WordPress大学
G
Google Developers Blog
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
P
Proofpoint News Feed
J
Java Code Geeks
U
Unit 42
云风的 BLOG
云风的 BLOG
阮一峰的网络日志
阮一峰的网络日志
N
Netflix TechBlog - Medium
宝玉的分享
宝玉的分享
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
D
Docker
V
Visual Studio Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Help Net Security
V
V2EX
T
Tailwind CSS 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
EF Core Named query filters
Karen Payne · 2026-05-19 · via DEV Community

Introduction

EF Core 10 introduces named query filters, an improvement to global query filters that makes common patterns like soft deletion and multitenancy easier to manage. In earlier versions, each entity type effectively had one combined filter, which meant disabling filters for a special query was all-or-nothing. With EF Core 10, filters can be given individual names, such as SoftDeletionFilter or TenantFilter, allowing developers to define multiple filters on the same entity and selectively disable only the ones needed for a specific LINQ query. This gives applications more precise control while keeping the default filtering behavior clean, consistent, and centralized. (learn.microsoft.com)

Topics covered

  • Creating filters
  • Ignoring filters
  • Using supplied language extensions for checking filter(s) exists for a model

Source code

  • The provided source code is fully documented.
  • SQL has been provided to create the database.

Source code samples Source code for language extension

Table schema for code samples

Employee schema, IsDeleted column for soft delete, IsManager indicates if the record is a manager.

Schema for Employee

Soft delete DbContext setup

SaveChanges event needs to be overridden so that a record is not removed, instead State is set to modified and IsDeleted column/property is set to true.

public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
    ChangeTracker.DetectChanges();

    foreach (var entry in ChangeTracker.Entries())
    {
        if (entry.State == EntityState.Deleted)
        {
            // Change state to modified and set delete flag
            entry.State = EntityState.Modified;
            entry.Property("IsDeleted").CurrentValue = true;
        }
    }

    return await base.SaveChangesAsync(cancellationToken);

}

public override int SaveChanges()
{

    ChangeTracker.DetectChanges();

    foreach (var entry in ChangeTracker.Entries())
    {
        if (entry.State == EntityState.Deleted)
        {
            // Change state to modified and set delete flag
            entry.State = EntityState.Modified;
            entry.Property("IsDeleted").CurrentValue = true;
        }
    }

    return base.SaveChanges();

}

Enter fullscreen mode Exit fullscreen mode

Filter setup

For the provided code sample, there is a filter for soft delete and a filter for if a record is a manager.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Employee>(entity =>
    {
        entity.Property(e => e.FirstName)
            .IsRequired()
            .HasMaxLength(50);
        entity.Property(e => e.LastName)
            .IsRequired()
            .HasMaxLength(50);

        entity.HasQueryFilter("SoftDelete", e => !e.IsDeleted);
        entity.HasQueryFilter("IsManager", e => e.IsManager);

    });

    OnModelCreatingPartial(modelBuilder);
}

Enter fullscreen mode Exit fullscreen mode

Performing a soft delete

In this case the overridden SaveChangesAsync is used which changes the State from Deleted to Modified.

AnsiConsole.MarkupLine is from Spectre.Console

private static async Task PerformDelete()
{

    SpectreConsoleHelpers.PrintPink();

    int id = 2;

    await using var context = new Context();
    var employee = await context.Employees.FirstOrDefaultAsync(x => x.Id == id);

    if (employee is not null)
    {
        context.Employees.Remove(employee).State = EntityState.Deleted;
        var affected = await context.SaveChangesAsync();
        AnsiConsole.MarkupLine(affected > 0
            ? $"[green]Successfully deleted employee with ID {id}.[/]"
            : $"[red]Failed to delete employee with ID {id}. Affected rows: {affected}[/]");
    }
    else
    {
        AnsiConsole.MarkupLine($"[yellow]Employee with ID {id} not found.[/]");
    }
}

Enter fullscreen mode Exit fullscreen mode

Ignore a filter

using var context = new Context();
var employees = context.Employees
    .IgnoreQueryFilters(["SoftDelete"])
    .ToList();

Enter fullscreen mode Exit fullscreen mode

Get query filter language extensions

These can be helpful when a developer doesn't have the DbContext source code.

public static class DbContextExtensions
{

    extension(DbContext context)
    {

        public bool HasQueryFilter<TEntity>()  where TEntity : class
        {
            var entityType = context.Model.FindEntityType(typeof(TEntity));
            return entityType?.GetDeclaredQueryFilters() != null;
        }

        public IReadOnlyCollection<IQueryFilter>? GetQueryFilters<TEntity>() where TEntity : class
        {
            var entityType = context.Model.FindEntityType(typeof(TEntity));
            return entityType?.GetDeclaredQueryFilters();
        }

        public IReadOnlyCollection<IQueryFilter> TryGetQueryFilters<TEntity>() where TEntity : class
        {
            var entityType = context.Model.FindEntityType(typeof(TEntity));
            var filters = entityType?.GetDeclaredQueryFilters();
            return filters ?? [];
        }

    }
}

Enter fullscreen mode Exit fullscreen mode

One sample

output for code sample below

private static void DisplayEmployeeQueryFilters()
{
    using var context = new Context();
    if (context.HasQueryFilter<Employee>())
    {
        var filters = context.GetQueryFilters<Employee>();

        if (filters is null) return;

        foreach (var (index, filter) in filters.Index())
        {
            AnsiConsole.MarkupLine($"{index, -4}" +
                                    $"[cyan]Name[/] {filter.Key} " +
                                    $"[cyan]Expression[/] {filter.Expression}");
        }
    }
    else
    {
        AnsiConsole.MarkupLine("[red]No query filters found for Employee entity.[/]");
    }
}

Enter fullscreen mode Exit fullscreen mode

Summary

The EF Core team has made it easy to set multiple query filters, and by following the instructions and sample code provided, developers can use named query filters.