简体   繁体   中英

Linq to Entities conditional WHERE

I'm currently running the following query:

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}

Now I need to make the where (a.PMId == lUserId || a.TLId == lInUserId) line conditional on if lUserId != 0 (use it if not 0, ignore it if 0).

Normally, I would declare the variable results then set it in an if statement, but I have no idea how to define this data structure. It shows as being defined as:

IQueryble<'a>

'a is new { int Id, string T, string C, string S}

Whats the best way to accomplish this?

You can use || operator in the query so if first condition is true, the second will not be evaluated and if first is false that is not equal to 0 second will be evaluated:

where lUserId ==0 || (a.PMId == lUserId || a.TLId == lInUserId)

What I understand is:

  • use the condition a.PMId == lUserId || a.TLId == lInUserId a.PMId == lUserId || a.TLId == lInUserId if and only if UserId != 0
  • Ignore that condition if lUserId ==0 If I understand the requirement correctly, then && will be the operator that you have to use here. since it will skip checking the second condition if the first condition is false(that is UserId == 0 ).

I think you are looking for this:

where (UserId != 0 && a.PMId == lUserId || a.TLId == lInUserId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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