本文介绍了向所有查询实体框架添加过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在所有实体框架请求中添加CompanyID过滤器,因为每个用户只能看到他们的记录。我不想在业务层中添加所有方法的过滤器(x => x.CompanyID == cID)。如何添加自动过滤请求。
I want add CompanyID filter to my all entity framework request.Because each user must see just their records.I dont want add filter (x=>x.CompanyID == cID) all methods in business layer.How can i add automaticly filter to requests.
我在DAL中的GetList方法
My GetList method in DAL
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();
}
}
Business
public List<FinanceData> GetAll()
{
return _financeDal.GetList(filter:x=>x.CompanyID==_cID);
}
推荐答案
您可以实现<$ c此类实体中的$ c> IHasCompanyId 接口。然后将存储库模式实现为:
You can implement IHasCompanyId
interface in such entities. And then implement repository pattern as:
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);
这篇关于向所有查询实体框架添加过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!