简体   繁体   中英

Linq to SQL - Multiple where clauses at runtime

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));
}
  if (!string.IsNullOrEmpty(reference))
        query = query.Where(tb => tb.Reference = reference));

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(...)

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