簡體   English   中英

LINQ語句中的多個OR子句

[英]Multiple OR clauses in LINQ statement

我有下面的LINQ查詢:

returnVal = context.ReservationRequests
   .Where(s => ((s.RequestStatusId.HasValue) &&
                (s.RequestStatusId.Value == ResStatusId)) &&
               ((string.IsNullOrEmpty(loggedInUserRole) 
                  || s.SubmitterGroupName == loggedInUserRole) 
                  ||(s.CreatedBy == ApplicationSecurityDirector.CurrentUserGuid)))                                                         
   .Skip(skip)
   .Take(take)
  .ToList();

該LINQ查詢應該執行的操作將調查ReservationRequests表並查找其中RequestStatusId =(suppliedRequestStatusId)和SubmitterGroupName應該等於登錄用戶角色的記錄(但是在某些情況下,用戶未分配給任何角色)它也應該返回用戶創建的任何請求。 因此,基本上,如果分配給特定組,則返回所有記錄;如果有的話,還返回由親自登錄創建的請求。

上面的查詢在用戶登錄到組的情況下工作正常,但是當用戶未分配給任何組時,它不會返回正確的結果。 如果未將人員分配到任何組,則應返回該用戶創建的所有記錄。

下面是我編寫的SQL查詢,該查詢返回所有案例的正確記錄量,我基本上需要LINQ才能像此sql一樣,但是我不確定這里缺少什么。

     SELECT *
  FROM [MyDB].[dbo].[ReservationRequests]
  where 
  (RequestStatusId = 2) 
  and 
  (SubmitterGroupName != null or SubmitterGroupName = null 
  or createdby = 'C5188D45-TEST-45BE-8C04-123455733A31')

有人可以調查我的LINQ查詢,看看為什么返回的記錄比我的SQL錯誤嗎? 謝謝,我已經看了一段時間了!

畢竟這里的建議是我更新的LINQ:

returnVal = context.ReservationRequests
.Where(s => ((s.RequestStatusId.HasValue) &&
(s.RequestStatusId.Value == ResStatusId)) &&
(s.SubmitterGroupName == loggedInUserRole ||
s.CreatedBy == ApplicationSecurityDirector.CurrentUserGuid))
.Skip(skip)
.Take(take)
.ToList();

那么問題:在loggingInUserRole為空的情況下,此查詢是否有效? 如果LoggedInUserRole為null,那么我只想返回已登錄用戶CreatedBy的記錄。

另一個更新:(2017年9月22日)上午9.54,所以我運行了該語句。 在將用戶分配給組但未將用戶分配給組而不是僅顯示已登錄用戶打開的請求的情況下,它會返回很多記錄。

incorrect records是相對的...我想它返回的記錄是正確的。 我們只能分析您在這里做什么以及區別在哪里:

在linq查詢中搜索

s.SubmitterGroupName == loggedInUserRole

在您搜索的SQL語句中

SubmitterGroupName != null or SubmitterGroupName = null 

SubmitterGroupName不能為null,並且不能同時為null。因此,我猜loggedInUserRole為null。 與or一起使用,因此總是如此。 您只需要搜索createdby = 'C5188D45-TEST-45BE-8C04-123455733A31'

另外,在linq查詢中

.Skip(skip).Take(take)

這在您的sql語句中丟失

所以我想你想要的是:

returnVal = context.ReservationRequests
.Where(s => ((s.RequestStatusId.HasValue) &&
(s.RequestStatusId.Value == ResStatusId)) &&
(s.SubmitterGroupName == loggedInUserRole || (s.SubmitterGroupName == null && s.CreatedBy == ApplicationSecurityDirector.CurrentUserGuid)))
.Skip(skip)
.Take(take)
.ToList();

我不完全確定為什么要在其中添加各種檢查,但這應該可行:

returnVal = context.ReservationRequests
.Where(s => RequestStatusId == ResStatusId &&
    (s.SubmitterGroupName == loggedInUserRole || s.CreatedBy == ApplicationSecurityDirector.CurrentUserGuid)
.Skip(skip)
.Take(take)
.ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM