如何解决带有动态参数的LINQ查询并执行Count操作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();
}
说明: 我想做的是,当传递诸如Country的PTypeId,BTypeId之类的参数时,它应该考虑该参数并根据该参数对行数进行计数。如果未传递任何参数,则应返回总行数。
结果:我总是得到状态为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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。