dynamic linq multiple vs single .where query

c# dynamic-linq linq

Question

Why do a single where query and numerous where inquiries provide different results?

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

query.ToString(); leads to:

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

and a single query that makes many 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");

leads to:

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

To allow for the variousWhere To make s significant, you must assign them toquery :

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

as wellWhere Chaining calls is possible. linq extension methods typically returnIEnumerable<TSource> and may therefore be chained.

If you apply chaining to your second query, it will appear as follows:

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

Since the calls don't alter the query, they instead return a new instance that represents the altered query. Therefore, the second example produces the large query, but the first example produces merely a straightforward where condition.



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