I am currently trying to add an order by to a LINQ query that will order by a datetime field in an EF object:
return this.SortingDirection.Equals("asc", StringComparison.InvariantCultureIgnoreCase) ? entities.OrderBy(e => e.ProcessStartTime) : entities.OrderByDescending(e => e.ProcessStartTime);
When the SortingDirection
is set to desc
it works fine. But when set to asc
I get no records!
Upon looking at SQL Server Profiler, it turns out that DateTime
objects are being formatted differently!
For DESC
:
ORDER BY [Project1].[StartTime] DESC',N'...@p__linq__22='2015-01-07 09:00:23',@p__linq__23='2015-01-07 09:00:23',@p__linq__24='2015-01-07 09:05:30',@p__linq__25='2015-01-07 09:05:30'
and for ASC
:
ORDER BY [Project1].[StartTime] ASC',N'...@p__linq__22='2015-07-01 09:00:23',@p__linq__23='2015-07-01 09:00:23',@p__linq__24='2015-07-01 09:05:30',@p__linq__25='2015-07-01 09:05:30'
Days and months have been swapped, causing the sql query to return no results.
This to me suggests that the IQueryable.OrderBy()
method is not using the correct local format / different format to OrderByDescending()
, could this be a bug in EF?
Is there something in my connection string I could add to enforce this or another way I could sort by these dates?
My setup:
Many thanks
You don't show your linq query, but two things come to mind immediately. First, SQL Server has its own globalization settings, and second, if dates are paramertized (which linq should always do) you shouldn't need to care about date string formats.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With