首页 > 解决方案 > 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 的所有行数。

我怎样才能得到结果。

标签: c#entity-frameworkentity-framework-corelinq-to-sqlasp.net-core-mvc

解决方案


出于某种原因,我认为您应该将 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();

推荐阅读