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 ru开发者_JAVA百科ns.
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(...)
精彩评论