如何在仓储模式下结合UnitOfWork与GetAll()实现可选参数的数据过滤
解决方案
核心思路是给每个筛选条件增加「参数是否为默认值」的前置判断,用户未选择的参数对应条件直接返回true,不会参与数据过滤:
- 先确认各筛选字段的默认值规则:
- 数值类型(
int类型的公司ID、客户ID、年份、产品组ID、剂型ID、场景ID等):未选择时默认值为0 - 字符串类型(许可区域、货币等):未选择时默认值为
null
- 数值类型(
- 修改
IndexPost方法中的过滤逻辑,修改后代码如下:
/********INDEX POST*********/ [HttpPost] public IActionResult Index(BudgetViewModel budget) { BudgetVM = new BudgetViewModel() { // 如果需要提交后保留用户选择的筛选值,替换下行代码为FBudget = budget.FBudget FBudget = new FBudget(), YearsList = _unitOfWork.Budget.GetYearsListForDropdown(), CompanyList = _unitOfWork.Budget.GetCompanyListForDropDown(), CustomerList = _unitOfWork.Budget.GetCustomerListForDropDown(), ProductGroupList = _unitOfWork.Budget.GetProductGroupListForDropDown(), LicensingAreaList = _unitOfWork.Budget.GetLicensingAreaListForDropDown(), PharmaFormList = _unitOfWork.Budget.GetPharmaFormListForDropDown(), LedgerScenarioList = _unitOfWork.Budget.GetLedgerScenarioListForDropDown(), CurrencyList = _unitOfWork.Budget.GetCurrencyListForDropdown(), // 修改后的过滤逻辑 RecordsList = _unitOfWork.Budget.GetAll( filter: b => // 年份:选了才生效 (budget.FBudget.Year == 0 || b.Year == budget.FBudget.Year) // 公司:选了才生效 && (budget.FBudget.CompanyId == 0 || b.CompanyId == budget.FBudget.CompanyId) // 客户:选了才生效 && (budget.FBudget.CustomerId == 0 || b.CustomerId == budget.FBudget.CustomerId) // 许可区域:选了才生效 && (string.IsNullOrEmpty(budget.FBudget.Customer?.LicensingArea) || b.Customer.LicensingArea == budget.FBudget.Customer.LicensingArea) // 产品组:选了才生效 && (budget.FBudget.ItemMaster.ProductGroupId == 0 || b.ItemMaster.ProductGroupId == budget.FBudget.ItemMaster.ProductGroupId) // 剂型:选了才生效 && (budget.FBudget.ItemMaster.PharmaFormId == 0 || b.ItemMaster.PharmaFormId == budget.FBudget.ItemMaster.PharmaFormId) // 货币:选了才生效 && (string.IsNullOrEmpty(budget.FBudget.Currency) || b.Currency == budget.FBudget.Currency) // 场景:选了才生效 && (budget.FBudget.LedgerTypeId == 0 || b.LedgerTypeId == budget.FBudget.LedgerTypeId), includeProperties: "ItemMaster,Customer" ) }; return View(BudgetVM); }
补充说明
EF Core会自动优化表达式中恒成立的条件,不会将无效的判断逻辑生成到最终执行的SQL语句中,不会产生额外性能开销。
内容的提问来源于stack exchange,提问作者chdev
相关产品推荐
相关产品推荐

