Often this sort of thing feels smoother to write using the fluent syntax, rather than the query syntax.
e.g.
IQueryable query = dataContext.Staffs;
if(name1 != null)
{
query = query.Where(x => x.name == name1);
}
So if name1
is null, you just don't do any Where()
call. If you have multiple different filters, all of which may or may not be required, and perhaps various different sort orders, I find this becomes a lot more manageable.
Edit for alex: OK, I was answering the question about adding a where clause only when a value is not null. In response to the other part of the question, I tried this out with Entity Framework 4 to see what SQL that LINQ produced. You do this by casting query
to an ObjectQuery
and calling .ToTraceString()
. The results were that the WHERE
clause came out as follows:
WHERE @p__linq__0 IS NULL OR [Extent1].[name] = @p__linq__1
So, yes, it's classic bad SQL, if you have an index on the name
column, don't expect it to be used.
Edit #2: Tried this again using LINQ to SQL rather than Entity Framework, with rather different results. This time, trying the query with name1
being null results in no WHERE
clause at all, as you'd hope; trying it with name1
being "a" resulted in a simple WHERE [t0].[name] = @p0
and @p0
sent as "a". Entity Framework does not seem to optimize thus. That's a bit worrying.
(@p__linq__2 IS NULL OR [Extent3].[ZZZ] = @p__linq__3)
than with[Extent3].[ZZZ] = @p__linq__3
when querying against a complex view – Mckameyname1 == null
. – Overbuild