Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by (asc|desc) in linq to SQL Server handles DateTime differently

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

like image 465
user2831628 Avatar asked Jan 09 '15 12:01

user2831628


1 Answers

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.

like image 113
Cylon Cat Avatar answered Nov 08 '22 12:11

Cylon Cat