Search code examples
c#linq-to-sqlwhere-clausedynamic-linq

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));
}

Solution

  •   if (!string.IsNullOrEmpty(reference))
            query = query.Where(tb => tb.Reference = reference));