Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Compare in Linq

Tags:

c#

linq

I am trying to use DateTime.Compare in Linq :

from ---  
where DateTime.Compare(Convert.ToDateTime(ktab.KTABTOM), DateTime.Now) < 1
select new 
{
-------
}

But this gives me an error :

LINQ to Entities does not recognize the method 'System.DateTime ConvertTimeFromUtc(System.DateTime, System.TimeZoneInfo)' method, and this method cannot be translated into a store expression  

This link suggests that we should use EntityFunctions to fix dateTime manipulation in Linq. But here I need to compare the complete date. Even this won't help me.

The date is in format yyyy-MM-dd.

like image 246
Nitish Avatar asked Nov 20 '13 07:11

Nitish


1 Answers

You don't need DateTime.Compare just write ktab.KTABTOM <= DateTime.Now

Examples with nullable DateTime:

doesn't compile

from p in Projects
where DateTime.Compare(DateTime.Now, p.EndDate) <= 0
select p.EndDate

and

from p in Projects
where DateTime.Now <= p.EndDate
select p.EndDate

translates into

SELECT 
[Extent1].[EndDate] AS [EndDate]
FROM [dbo].[Project] AS [Extent1]
WHERE  CAST( SysDateTime() AS datetime2) <= [Extent1].[EndDate]

Examples without nullable DateTime:

from p in Projects
where DateTime.Compare(DateTime.Now, p.StartDate) <= 0
select p.StartDate

and

from p in Projects
where DateTime.Now <= p.StartDate
select p.StartDate

both translates into

SELECT 
[Extent1].[StartDate] AS [StartDate]
FROM [dbo].[Project] AS [Extent1]
WHERE (SysDateTime()) <= [Extent1].[StartDate]
like image 120
Guru Stron Avatar answered Nov 12 '22 20:11

Guru Stron