You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为所有实体设置全局条件隐藏已删除实体?EF Core技术问询

EF Core 全局配置软删除查询过滤

1. 定义统一软删除接口

先创建一个包含软删除标识属性的接口,让所有需要隐藏已删除数据的实体实现该接口:

public interface ISoftDelete
{
    bool? IsDeleted { get; set; }
}

2. 让实体实现接口

将你的实体类继承该接口,以BankAccountCurrencyType为例:

public class BankAccountCurrencyType : ISoftDelete
{
    // 实体原有属性...
    public bool? IsDeleted { get; set; }
}

3. 批量配置全局查询过滤

在OnModelCreating方法中遍历所有实体类型,对实现了ISoftDelete接口的实体统一添加查询过滤:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // 遍历模型中所有实体类型
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        // 判断当前实体是否实现了ISoftDelete接口
        if (typeof(ISoftDelete).IsAssignableFrom(entityType.ClrType))
        {
            // 构建查询过滤的表达式树
            var parameter = Expression.Parameter(entityType.ClrType, "x");
            var isDeletedProperty = Expression.Property(parameter, nameof(ISoftDelete.IsDeleted));
            
            // 构造条件:x.IsDeleted == false || x.IsDeleted == null
            var filterExpression = Expression.OrElse(
                Expression.Equal(isDeletedProperty, Expression.Constant(false, typeof(bool))),
                Expression.Equal(isDeletedProperty, Expression.Constant(null, typeof(bool?)))
            );
            
            // 为实体添加查询过滤
            modelBuilder.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(filterExpression, parameter));
        }
    }
}

额外说明

如果需要临时绕过全局过滤查询已删除数据,可以使用IgnoreQueryFilters()方法:

var deletedRecords = dbContext.BankAccountCurrencyTypes.IgnoreQueryFilters()
                                                      .Where(x => x.IsDeleted == true)
                                                      .ToList();

内容的提问来源于stack exchange,提问作者Zeynab Rostami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 18:14:54