首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在LINQ to Entities异常中不支持指定的类型成员'Date‘

在LINQ to Entities异常中不支持指定的类型成员'Date‘
EN

Stack Overflow用户
提问于 2012-07-22 10:24:37
回答 9查看 74.4K关注 0票数 110

在实现以下语句时,我得到了一个异常。

 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.

我知道异常是什么意思,但我不知道如何摆脱它。有什么帮助吗?

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 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);
票数 105
EN

Stack Overflow用户

发布于 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

票数 239
EN

Stack Overflow用户

发布于 2013-12-10 01:31:05

对于EF6,请使用DbFunctions.TruncateTime(mydate)。

票数 39
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11597373

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档