Add filter to all query entity framework

前端 未结 4 1567
孤街浪徒
孤街浪徒 2020-12-18 11:07

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 bu

4条回答
  •  春和景丽
    2020-12-18 11:46

    You can implement IHasCompanyId interface in such entities. And then implement repository pattern as:

    public class MyRepository
    {
        public MyRepository(DbContext dbContext, int companyID)
        {
            if (dbContext == null) 
                throw new ArgumentNullException("Null DbContext");
            DbContext = dbContext;
            DbSet = DbContext.Set();
    
            CompanyID = companyID;
        }
    
        protected DbContext DbContext { get; set; }
        protected int CompanyID  { get; set; }
    
        protected DbSet DbSet { get; set; }
    
        // Add filter here
        public virtual IQueryable GetAll()
        {
            if(typeof(IHasCompanyID).IsAssignableFrom(typeof(T)))
                return DbSet.Where(x => x.CompanyID == CompanyID);
            else 
                return DbSet;
        }
    }
    

    And initialize _financeDal as:

    var _financeDal = new MyRepository(dbContext, companyID);
    

提交回复
热议问题