c# - LINQ 动态参数查询并执行计数操作 ASP.NET Core 3.1
问题描述
我正在尝试使用动态过滤器参数查询表。目标是计算与过滤器匹配的行数。
一个非常简化的控制器版本
public async Task<IActionResult> Index(string PTypeId = null, string Country = null, string BTypeId = null)
{
int countList = await _context.InfoProducts.Where(obj => obj.Status.Equals(100) && ((PTypeId == null || obj.PTypeId == PTypeId) || (BTypeId == null || obj.BTypeId == BTypeId) || (Country == null || obj.Country == Country ))).CountAsync();
}
说明:我想要做的是当传递一个参数时,例如 PTypeId,BTypeId of Country,它应该考虑该参数并根据该参数计算行数。如果没有传递参数,那么它应该返回总行数。
结果:我总是得到状态为 100 的总行数。即使传递了一个参数,它也会忽略它并在所有情况下返回总行数。
我什至尝试对参数进行硬编码,但它仍然返回状态为 100 的所有行数。
我怎样才能得到结果。
解决方案
出于某种原因,我认为您应该将 guery 更改为:
var countList = await _context.InfoProducts.Where(obj => obj.Status.Equals(100) && ((PTypeId == null || obj.PTypeId == PTypeId)) && ( (BTypeId == null || obj.BTypeId == BTypeId)) && ((Country == null || obj.Country == Country ))).CountAsync();
推荐阅读
- sql - SQL 到 JPQL 加入请求
- java - 如何以方便的方式检查多个元素中的任何一个是否在列表中?
- c# - 如何在字典中添加数据
,字符串> - java - Spring Boot 2 Maven 项目在 Intellij 上运行但不在 Tomcat 上
- r - 使用 R 进行模拟研究中的最大似然估计
- python - 在 FTP 中使用 Python 创建年/月/日文件夹结构
- sql-server - 从 t-sql 中的列中提取帖子和地址
- datadog - Datadog - 如果指标的值在三天内没有变化,则会向您发出警报
- java - 使用套接字编程的Java文件传输
- mysql - 如何将excel文件导入MySQL Workbench?