在实现以下语句时,我得到了一个异常。
DateTime result;
if (!DateTime.TryParse(rule.data, out result))
return jobdescriptions;
if (result < new DateTime(1754, 1, 1)) // sql can't handle dates before 1-1-1753
return jobdescriptions;
return jobdescriptions.Where(j => j.JobDeadline.Date == Convert.ToDateTime(rule.data).Date );
异常
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
我知道异常是什么意思,但我不知道如何摆脱它。有什么帮助吗?
发布于 2012-07-22 11:22:51
LINQ to Entities无法将大多数SQL方法(包括您使用的强制转换)转换为.NET,因为没有等效的SQL语句。
解决方案是在LINQ语句外部使用Date方法,然后传入一个值。看起来好像是Convert.ToDateTime(rule.data).Date导致了这个错误。
在DateTime属性上调用Date也不能转换为SQL,因此解决方法是比较.Year .Month和.Day属性,因为它们只是整数。
var ruleDate = Convert.ToDateTime(rule.data).Date;
return jobdescriptions.Where(j => j.Deadline.Year == ruleDate.Year
&& j.Deadline.Month == ruleDate.Month
&& j.Deadline.Day == ruleDate.Day);
发布于 2012-07-22 21:40:36
您可以使用的方法来实现Date
属性到SQL的正确转换:
using System.Data.Objects; // you need this namespace for EntityFunctions
// ...
DateTime ruleData = Convert.ToDateTime(rule.data).Date;
return jobdescriptions
.Where(j => EntityFunctions.TruncateTime(j.JobDeadline) == ruleData);
更新:EntityFunctions
在EF6中已弃用,请使用DbFunctions.TruncateTime
发布于 2013-12-10 01:31:05
对于EF6,请使用DbFunctions.TruncateTime(mydate)。
https://stackoverflow.com/questions/11597373
复制相似问题