The following LINQ to SQL query is splitting the date into pieces. It seems odd that a date comparison would use the following generated SQL statement.
var customers =
(from c in db.customers
where c.servhists.Any(sh => sh.donedate.Value.Date >= startDate.Date
&& sh.donedate.Value.Date <= endDate.Date
&& sh.donedate.Value.AddDays(triggerDays).Date <= DateTime.Now.Date)
produces the following SQL Query for MS SQL Server 2008
…
WHERE (DATEADD(HOUR, -DATEPART(HOUR, [t3].[donedate]), DATEADD(MINUTE, -DATEPART(MINUTE, [t3].[donedate]), DATEADD(SECOND, -DATEPART(SECOND, [t3].[donedate]), DATEADD(MILLISECOND, -DATEPART(MILLISECOND, [t3].[donedate]), [t3].[donedate])))) >= '6/7/2010') AND (DATEADD(HOUR, -DATEPART(HOUR, [t3].[donedate]), DATEADD(MINUTE, -DATEPART(MINUTE, [t3].[donedate]), DATEADD(SECOND, -DATEPART(SECOND, [t3].[donedate]), DATEADD(MILLISECOND, -DATEPART(MILLISECOND, [t3].[donedate]), [t3].[donedate])))) <= '8/8/2010') AND (DATEADD(HOUR, -DATEPART(HOUR, DATEADD(ms, (CONVERT(BigInt,3 * 86400000)) % 86400000, DATEADD(day, (CONVERT(BigInt,3 * 86400000)) / 86400000, [t3].[donedate]))), DATEADD(MINUTE, -DATEPART(MINUTE, DATEADD(ms, (CONVERT(BigInt,3 * 86400000)) % 86400000, DATEADD(day, (CONVERT(BigInt,3 * 86400000)) / 86400000, [t3].[donedate]))), DATEADD(SECOND, -DATEPART(SECOND, DATEADD(ms, (CONVERT(BigInt,3 * 86400000)) % 86400000, DATEADD(day, (CONVERT(BigInt,3 * 86400000)) / 86400000, [t3].[donedate]))), DATEADD(MILLISECOND, -DATEPART(MILLISECOND, DATEADD(ms, (CONVERT(BigInt,3 * 86400000)) % 86400000, DATEADD(day, (CONVERT(BigInt,3 * 86400000)) / 86400000, [t3].[donedate]))), DATEADD(ms, (CONVERT(BigInt,3 * 86400000)) % 86400000, DATEADD(day, (CONVERT(BigInt,3 * 86400000)) / 86400000, [t3].[donedate])))))) <= '10/22/2010')
..
donedate is a nullable column of type DateTime
I can’t imagine this helps performance much. Can anyone suggest a fix/correction that I could do to get rid of this ugly SQL?
The SQL that you saw generated is a result of how the use of the Date property on a column gets rendered into SQL by LINQ. Change your date math to avoid the use of the Date property and other date operations on the column itself. Instead, perform as much of the date math operations as you can on the variable that you are comparing to the column.
This might need some further tweaking so compare results from the one you know works to this before switching. This should be enough to give you the idea.