繁体   English   中英

LINQ:WHERE子句中的IF条件不起作用

[英]LINQ: IF condition in WHERE clause not working

我有以下LINQ查询,它应该查看表Products并返回传递参数的记录,它们是:搜索项(字符串)和3个不同“类型”的布尔值。

   var query = context.Products
                       .Where(a => request.SearchTerm == null || a.Name.Contains(request.SearchTerm))
    .Where(a => (request.isTypeA == false || (a.OrderType == "X" && request.isTypeA == true)) ||
    (request.typeB == false || (a.OrderType == "R" && request.typeB == true))
    || (request.typeC == false || (a.OrderType == "D" && request.typeC == true)))
    .Where (a=> a.OrderType != "U")
    .Where(a => a.IsInactiveFlag == false )
    .OrderBy(a => a.OrderType)
    .Select(c => new ProductType   
        {
            ProductTypeId = c.ProductTypeId,
            IsSelected = false,
            OrderType = c.OrderType,
            Name = c.Name,
            IsInactiveFlag = c.IsInactiveFlag
        });

问题 :问题是查询总是通过查看传递的searchTerm来返回记录,但它没有考虑布尔参数。例如,我可以说我的搜索参数是:searchTerm =“reference”,isTypeA = false,isTypeB = false和isTypeC = true。 上面的查询将返回所有不同类型的searchTerm“reference”的所有记录,而不仅仅是TypeC。

在发布这个问题之前我搜索了很多,但没有什么是我遇到的。 请让我知道我做错了什么。 谢谢!

尝试这个

   var query = context.Products
                   .Where(a => request.SearchTerm == null || a.Name.Contains(request.SearchTerm))
.Where(a => (a.OrderType == "X" && request.isTypeA)
|| (a.OrderType == "R" && request.typeB)
|| (a.OrderType == "D" && request.typeC))
.Where (a=> a.OrderType != "U")
.Where(a => a.IsInactiveFlag == false )
.OrderBy(a => a.OrderType)
.Select(c => new ProductType   
    {
        ProductTypeId = c.ProductTypeId,
        IsSelected = false,
        OrderType = c.OrderType,
        Name = c.Name,
        IsInactiveFlag = c.IsInactiveFlag
    });

你应该明确关于过滤值的每个测试旁边的OrderType的包含/排除的旁路标准,它作为一个开关....

  var query = context.Products
                       .Where(a => request.SearchTerm == null || a.Name.Contains(request.SearchTerm))
    .Where(a => (request.isTypeA == false && a.OrderType != "X" ) || (a.OrderType == "X" && request.isTypeA == true)) ||
    (request.typeB == false && a.OrderType != "R" )|| (a.OrderType == "R" && request.typeB == true))
    || (request.typeC == false && a.OrderType != "D" ) || (a.OrderType == "D" && request.typeC == true)))
    .Where (a=> a.OrderType != "U")
    .Where(a => a.IsInactiveFlag == false )
    .OrderBy(a => a.OrderType)
    .Select(c => new ProductType   
        {
            ProductTypeId = c.ProductTypeId,
            IsSelected = false,
            OrderType = c.OrderType,
            Name = c.Name,
            IsInactiveFlag = c.IsInactiveFlag
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM