如何在 Linq-to-Entities 查询中使用 DateTime.AddXXXX 函数?
我尝试在查询中使用 AddMonths
List<Entities.Subscriber> items = (from s in context.Subscribers
where s.Validated == false && s.ValidationEmailSent == true && s.SubscriptionDateTime < DateTime.Now.AddMonths(-1)
select s).ToList();
但收到错误:
LINQ to Entities 无法识别方法“System.DateTime” AddMonths(Int32)'方法,并且该方法不能被翻译成 存储表达式。
有没有办法在我的查询中使用这个函数?
I am trying to use AddMonths
in a query
List<Entities.Subscriber> items = (from s in context.Subscribers
where s.Validated == false && s.ValidationEmailSent == true && s.SubscriptionDateTime < DateTime.Now.AddMonths(-1)
select s).ToList();
But I recieve an error :
LINQ to Entities does not recognize the method 'System.DateTime
AddMonths(Int32)' method, and this method cannot be translated into a
store expression.
Is there a way I can use this function inside my query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对此最简单的解决方法是在使用 LINQ 之前计算出一次时间限制:
或更易读的 IMO:
此处使用查询表达式并与
true
和false
在我看来是丑陋的(当然,除非你的属性是Nullable
类型)。The simplest fix to this is to work out the time limit once before using LINQ:
Or more readably IMO:
There's no benefit in using a query expression here, and explicit comparisons with
true
andfalse
are ugly IMO (unless your properties are of typeNullable<bool>
of course).Jon Skeet 已经提供了一个简单的修复,但如果您希望在数据库上运行
DateTime.Now.AddMonths
位,请尝试EntityFunctions.AddMonths
方法。这是一种更通用的方法,当您无法在客户端上廉价或正确地复制表达式时特别有用。
Jon Skeet has already provided a simple fix, but if you want the
DateTime.Now.AddMonths
bit to run on the database, try theEntityFunctions.AddMonths
method.This is a more general approach that is especially useful when you cannot replicate the expression cheaply or correctly on the client.
您可以将代码更改为:
您必须这样做,因为 AddMonth 是一个 .NET 函数,无法通过 Linq to Entities 转换为 SQL。在代码中执行计算,然后使用生成的日期时间即可。
You can change your code to:
You have to do this because AddMonth is a .NET function that can't be translated into SQL by Linq to Entities. Perform the calculation in your code and then use the resulting datetime will work.