LINQ to Entities 异常不支持指定的类型成员“日期" [英] The specified type member 'Date' is not supported in LINQ to Entities Exception

查看:31
本文介绍了LINQ to Entities 异常不支持指定的类型成员“日期"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在执行以下语句时遇到异常.

I got a exception while implementing the following statements.

 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.

我知道异常意味着什么,但我不知道如何摆脱它.有什么帮助吗?

I know what the exception means but i don't know how to get rid of it. Any help?

推荐答案

LINQ to Entities 无法将大多数 .NET Date 方法(包括您使用的强制转换)转换为 SQL,因为没有等效的 SQL.

LINQ to Entities cannot translate most .NET Date methods (including the casting you used) into SQL since there is no equivalent SQL.

解决方案是在 LINQ 语句之外使用 Date 方法,然后传入一个值.看起来好像 Convert.ToDateTime(rule.data).Date 导致了错误.

The solution is to use the Date methods outside the LINQ statement and then pass in a value. It looks as if Convert.ToDateTime(rule.data).Date is causing the error.

在 DateTime 属性上调用 Date 也无法转换为 SQL,因此解决方法是比较 .Year .Month 和 .Day 属性,因为它们只是整数,因此可以转换为 LINQ.

Calling Date on a DateTime property also cannot be translated to SQL, so a workaround is to compare the .Year .Month and .Day properties which can be translated to LINQ since they are only integers.

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);

这篇关于LINQ to Entities 异常不支持指定的类型成员“日期"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆