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

时间:2016-07-18 15:55:31

标签: c# mysql sql linq

我有以下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。

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

2 个答案:

答案 0 :(得分:0)

试试这个

   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
    });

答案 1 :(得分:0)

你应该明确关于过滤值的每个测试旁边的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
        });