5

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Nitish
  • 13,845
  • 28
  • 135
  • 263

1 Answers1

12

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]
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 3
    Bear in mind that in .NET, comparing DateTime directly will ignore time zones, and count only ticks, so that if the DateTimes are not both in the same time zone, the comparison will be wrong. – Falcon Momot May 08 '16 at 09:51