Multiple where clauses at runtime with Linq to SQL

c# dynamic-linq linq-to-sql where-clause

Question

I am trying to accomplish this but only my first where clause is getting used when the query runs.

This needs to for for .Net 3.5 so the WhereIf in 4.0 is not usable.

var query =
    from tb in dataContext.TableOne
    where tb.DateTimeCreated >= fromDate && 
        tb.DateTimeCreated <= toDate.AddDays(1) 
    select tb;

if (!string.IsNullOrEmpty(reference))
{
    query.Where(tb => tb.Reference = reference));
}
1
0
2/12/2019 7:11:07 AM

Accepted Answer

  if (!string.IsNullOrEmpty(reference))
        query = query.Where(tb => tb.Reference = reference));
3
12/8/2010 1:15:56 PM

Popular Answer

Try

Just do it in "one"

var query = (from tb in dataContext.TableOne
                      where (tb.DateTimeCreated >= fromDate && tb.DateTimeCreated <= toDate.AddDays(1)) && (string.IsNullOrEmpty(reference) || tb.Reference == reference)
                      select tb
               );

or as Ives says, do:

query = query.Where(...)


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow