EF 6 - 注入where子句

时间:2016-11-16 20:15:01

标签: c# .net entity-framework-6

有没有办法为EF正在运行的所有查询普遍添加where子句?我希望所有查询都使用" entity.Active == true"例如

2 个答案:

答案 0 :(得分:1)

某些第三方库允许过滤查询:Entity Framework Filter Library List

免责声明:我是该项目的所有者Entity Framework Plus

Wiki:EF +查询过滤器

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

示例:

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

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

答案 1 :(得分:0)

最简单的方法(没有实现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);
}