[英]Linq to Entities conditional WHERE
我當前正在運行以下查詢:
var results = from c in _context.Cs
join a in _context.Ca on c.Id equals a.CId
where c.Status == "A"
where c.CtId == ctId
where c.FY == fYear
where (a.PMId == lUserId || a.TLId == lInUserId)
select new { c.Id, c.T, c.C, c.S } into x
group x by new {x.Id, x.T, x.C, x.S} into g
orderby g.Key.T, g.Key.C, g.Key.S
select new { Id = g.Key.Id, T = g.Key.T, C = g.Key.C, S = g.Key.S}
現在,我需要將where (a.PMId == lUserId || a.TLId == lInUserId)
行作為條件,如果lUserId!= 0(如果不為0,則使用它;如果為0,則忽略它)。
通常,我將聲明變量results
然后在if語句中對其進行設置,但是我不知道如何定義此數據結構。 它顯示為:
IQueryble<'a>
'a is new { int Id, string T, string C, string S}
最好的方法是什么?
您可以使用||
查詢中的運算符,因此,如果第一個條件為true,則將不評估第二個條件;如果first為false,則不等於0秒將被評估:
where lUserId ==0 || (a.PMId == lUserId || a.TLId == lInUserId)
我的理解是:
a.PMId == lUserId || a.TLId == lInUserId
a.PMId == lUserId || a.TLId == lInUserId
當且僅當UserId != 0
lUserId ==0
則忽略該條件。如果我正確理解了要求,那么&&
將是您在此處必須使用的運算符。 因為如果第一個條件為false(即UserId == 0
),它將跳過檢查第二個條件 。 我認為您正在尋找:
where (UserId != 0 && a.PMId == lUserId || a.TLId == lInUserId)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.