如何使用ToShortDateString在LINQ lambda表达式? [英] How to use ToShortDateString in linq lambda expression?
问题描述
我需要调用ToShortDateString在LINQ查询起诉lambda表达式:
I need to call ToShortDateString in a linq query suing lambda expressions:
toRet.Notification = Repositories
.portalDb.portal_notifications.OrderByDescending(p => p.id)
.FirstOrDefault(p => p.date.ToShortDateString() == shortDateString);
但我得到的错误:
but I get the error:
System.NotSupportedException类型的异常出现在
System.Data.Entity.dll但在用户代码中没有处理
An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code
其他信息:LINQ实体无法识别方法
位System.String ToShortDateString()'方法,和这种方法不能为
转换成店铺表达
Additional information: LINQ to Entities does not recognize the method 'System.String ToShortDateString()' method, and this method cannot be translated into a store expression.
我能做些什么,考虑到我确实需要使用 ToShortDateString()
?
What can I do, considering that I do need to use ToShortDateString()
?
感谢。
推荐答案
您不应该强迫字符串比较时,你的工作是什么同是日期/时间数据 - 只要你逼字符串比较,你会突然有应对的如何的字符串格式化
You shouldn't be forcing a string comparison when what you're working with is Date/time data - as soon as you force string comparisons, you're suddenly having to deal with how the strings are formatted.
相反,碰到这样的:
var endDate = targetDate.AddDays(1);
toRet.Notification = Repositories
.portalDb.portal_notifications.OrderByDescending(p => p.id)
.FirstOrDefault(p => p.date >= targetDate && p.date < endDate);
(假设 targetDate
是什么的DateTime
变量,你必须被用来制作 shortDateString
在你的代码,并且已经是日期时间
没有时间值)
(Assuming that targetDate
is whatever DateTime
variable you had that was used to produce shortDateString
in your code, and is already a DateTime
with no time value)
这篇关于如何使用ToShortDateString在LINQ lambda表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!