dynamic linq multiple vs single .where query

c# dynamic-linq linq

Question

Why does the single where query give a different result than multiple where queries ?

query.Where("666 = ID");
query.Where("ActiveFrom < @0 && ActiveTo > @1 && ValidFrom < DateTime.Now && ValidTo > DateTime.Now", toDate, fromDate);

query.ToString(); results in :

SELECT  *
    FROM [Country] AS [Extent1]
    WHERE 666 = [Extent1].[ID]

and the same query with multiple where calls

query = query.Where("ActiveFrom < @0", toDate);
query = query.Where("ActiveTo > @0", fromDate);
query = query.Where("ValidFrom < DateTime.Now");
query = query.Where("ValidTo > DateTime.Now");

results in :

SELECT  *
FROM [Country] AS [Extent1]
WHERE (666 = [Extent1].[ID]) AND 
([Extent1].[ActiveFrom] < convert(datetime2, '2016-10-23 11:40:35.9538054', 121)) AND 
([Extent1].[ActiveTo] > convert(datetime2, '2016-06-23 11:40:35.9518052', 121)) AND
([Extent1].[ValidFrom] < (SysDateTime())) AND 
([Extent1].[ValidTo] > (SysDateTime()))
1
3
8/23/2016 10:29:20 AM

Accepted Answer

In order for the different Wheres to be relevant you need to assign them back to query:

//instead of:
query.Where("666 = ID");
query.Where("ActiveFrom < @0 && ActiveTo > @1 && ValidFrom < DateTime.Now && ValidTo > DateTime.Now", toDate, fromDate);

//do:
query = query.Where("666 = ID");
query = query.Where("ActiveFrom < @0 && ActiveTo > @1 && ValidFrom < DateTime.Now && ValidTo > DateTime.Now", toDate, fromDate);

Also the Where calls can be chained. Most linq extension methods return IEnumerable<TSource> and therefore can be chained.

Applying the chaining on your second query it will look like this:

query = query.Where("ActiveFrom < @0", toDate)
             .Where("ActiveTo > @0", fromDate)
             .Where("ValidFrom < DateTime.Now")
             .Where("ValidTo > DateTime.Now");
2
9/29/2017 6:10:37 PM

Popular Answer

Because the calls dont modify the query, they return a new instance representing the modified query instead. Thus the second example results in the big query whereas the first results in a simple where condition only.



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