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:
- .NET 4.5
- Entity Framework 5.0.0
- SQL Server 2012 Standard
Many thanks