将过滤器添加到所有查询实体框架

时间:2015-03-25 16:51:49

标签: c# entity-framework

我想将CompanyID过滤器添加到我的所有实体框架请求中。因为每个用户必须只看到他们的记录。我不想在业务层中添加过滤器(x => x.CompanyID == cID)所有方法。我怎么能添加自动过滤到请求。

我在DAL中的GetList方法

     public List<TEntity> GetList(Expression<Func<TEntity, bool>> filter)
    {
        using (var context = new TContext())
        {

            return filter == null
                ? context.Set<TEntity>().ToList()
                : context.Set<TEntity>().Where(filter).ToList();
        }
    }

业务

   public List<FinanceData> GetAll()
        {
            return _financeDal.GetList(filter:x=>x.CompanyID==_cID);
        }

4 个答案:

答案 0 :(得分:2)

您可以在此类实体中实施IHasCompanyId接口。然后将存储库模式实现为:

public class MyRepository<T>
{
    public MyRepository(DbContext dbContext, int companyID)
    {
        if (dbContext == null) 
            throw new ArgumentNullException("Null DbContext");
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();

        CompanyID = companyID;
    }

    protected DbContext DbContext { get; set; }
    protected int CompanyID  { get; set; }

    protected DbSet<T> DbSet { get; set; }

    // Add filter here
    public virtual IQueryable<T> GetAll()
    {
        if(typeof(IHasCompanyID).IsAssignableFrom(typeof(T)))
            return DbSet.Where(x => x.CompanyID == CompanyID);
        else 
            return DbSet;
    }
}

并将_financeDal初始化为:

var _financeDal = new MyRepository<TEntity>(dbContext, companyID);

答案 1 :(得分:1)

Entity Framework Core 2.0 中,您可以使用Global Query Filters

  1. 仅向一个实体添加过滤器:

    public interface IDelete
    {
        bool IsDeleted { get; set; }
    }
    
    public class Blog : IDelete
    {        
        public int BlogId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
    
        public List<Post> Posts { get; set; }
    }
    
    public class Post : IDelete
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public bool IsDeleted { get; set; }
    
        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
    
    // Default method inside the DbContext or your default Context
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {         
        base.OnModelCreating(builder);  
    
        modelBuilder.Entity<Blog>()
                    // Add Global filter to the Blog entity
                    .HasQueryFilter(p => p.IsDeleted == false);
    
        modelBuilder.Entity<Post>()
                    // Add Global filter to the Post entity
                    .HasQueryFilter(p => p.IsDeleted == false);
    }
    
  2. 如果实体太多,第一种方法不好,请使用以下代码将全局过滤器应用于所有实体(魔术方法):

    public static class ModelBuilderExtension
    {
        public static void ApplyGlobalFilters<TInterface>(this ModelBuilder modelBuilder, Expression<Func<TInterface, bool>> expression)
        {
            var entities = modelBuilder.Model
                .GetEntityTypes()
                .Where(e => e.ClrType.GetInterface(typeof(TInterface).Name) != null)
                .Select(e => e.ClrType);
            foreach (var entity in entities)
            {
                var newParam = Expression.Parameter(entity);
                var newbody = ReplacingExpressionVisitor.Replace(expression.Parameters.Single(), newParam, expression.Body);    
                modelBuilder.Entity(entity).HasQueryFilter(Expression.Lambda(newbody, newParam));
            }
        }
    }
    
    // Default method inside the DbContext or your default Context
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    
        modelBuilder.Entity<Blog>();
        modelBuilder.Entity<Post>();
    
        builder.ApplyGlobalFilters<IDelete>(e => e.IsDeleted == false);
    }
    

查询将是:

    exec sp_executesql N'SELECT [x].[BlogId], [x].[Name], [x].[Url]
    FROM [dbo].[Blog] AS [x]
    WHERE [x].[IsDeleted] = 0'

答案 2 :(得分:1)

您建议的所有内容在以下情况下均不起作用:HasQueryFilter电源,但对于每个HTTP请求而言。 ApplyGlobalFilters / OnModelCreating一次应用于模型创建。但是,如果您使用不同的请求参数重新加载页面-过滤掉DbSet时不会考虑它们。 如果您将过滤器添加到GetAll调用-另一个调用'Include'-实体将没有此过滤器。 我们需要一种真正的全局机制来按特定条件过滤掉DbSet-每个请求可能会更改(页面刷新)。

答案 3 :(得分:0)

您还可以扩展object context并添加一个返回IQueryable

的扩展方法

喜欢

public class CustomdbContext : DbContext
{       
    public IQueryable<TEntity> ApplyCustomerFilter<TEntity>(IQueryable<TEntity> query) where TEntity : Customer 
    {
         return query.Where(x => x.CustomerId == customerctxId);
    }
}