Oct*_*ure 9 c# linq entity-framework
我需要在一个linq查询中使用lambda表达式调用ToShortDateString:
toRet.Notification = Repositories
.portalDb.portal_notifications.OrderByDescending(p => p.id)
.FirstOrDefault(p => p.date.ToShortDateString() == shortDateString);
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
System.Data.Entity.dll中出现"System.NotSupportedException"类型的异常,但未在用户代码中处理
附加信息:LINQ to Entities无法识别方法'System.String ToShortDateString()'方法,并且此方法无法转换为存储表达式.
考虑到我确实需要使用,我该怎么办ToShortDateString()
?
谢谢.
Ser*_*kiy 22
Linq to Entities无法将ToSortDateString
方法转换为SQL代码.你不能在服务器端调用它.将过滤移动到客户端(将所有数据从服务器传输到客户端),或者考虑使用服务器端函数来获取日期部分日期(您应该传递DateTime
对象而不是shortDateString
):
EntityFunctions.TruncateTime(p.date) == dateWithoutTime
Run Code Online (Sandbox Code Playgroud)
当您使用的是日期/时间数据时,您不应该强制进行字符串比较-强制进行字符串比较后,您突然不得不处理如何格式化字符串。
相反,请执行以下操作:
var endDate = targetDate.AddDays(1);
toRet.Notification = Repositories
.portalDb.portal_notifications.OrderByDescending(p => p.id)
.FirstOrDefault(p => p.date >= targetDate && p.date < endDate);
Run Code Online (Sandbox Code Playgroud)
(假设这targetDate
是DateTime
您shortDateString
在代码中用于生成的变量,并且已经是DateTime
没有时间值的变量)
归档时间: |
|
查看次数: |
16337 次 |
最近记录: |