Linq中的DateTime.Compare

时间:2013-11-20 07:09:53

标签: c# linq

我正在尝试在Linq中使用DateTime.Compare:

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

但这给了我一个错误:

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链接表明我们应该使用EntityFunctions来修复Linq中的dateTime操作。但在这里我需要比较完整的日期。即使this也不会帮助我。

日期格式为yyyy-MM-dd。

1 个答案:

答案 0 :(得分:8)

您只需撰写DateTime.Compare

即可ktab.KTABTOM <= DateTime.Now

可以为空的DateTime示例:

无法编译

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

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

转换为

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

没有可空日期的示例:

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

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

都转化为

SELECT 
[Extent1].[StartDate] AS [StartDate]
FROM [dbo].[Project] AS [Extent1]
WHERE (SysDateTime()) <= [Extent1].[StartDate]