繁体   English   中英

Linq to Entities有条件的位置

[英]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.

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