EF 6 - 注入where子句

问题描述:

是否有一种方法可以在EF正在运行的所有查询中通用添加where子句?我希望所有的查询与运行“entity.Active ==真”,例如EF 6 - 注入where子句

最简单的方法(不实现QueryTranslator接口)是为您的上下文这样

public static IQyertable<YourEntity> OnlyActiveEntities(this YourDbContext context, Action<DbSet<YourEntity>> setConfigurator = null) 
{ 
    var dbSet = context.Set<YourEntity>(); 
    setConfigurator?.Invoke(dbSet); 

    return context.Set<YourEntity>().AsQueriable().Where(entity => entity.Active == true); 
} 

一些第三方创建扩展方法库允许过滤查询:Entity Framework Filter Library List

免责声明:我的项目Entity Framework Plus

维基的主人:EF +查询过滤器

此功能正是你要找的。您可以添加全局过滤器来过滤所有查询。

实施例:

// using Z.EntityFramework.Plus; // Don't forget to include this. 

QueryFilterManager.Filter<ISoftDelete>(q => q.Where(x => x.IsActive));