簡體   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