如何在Linq-to-Entities查询中使用DateTime.AddXXXX函数? [英] How can i use DateTime.AddXXXX functions in a Linq-to-Entities query?
问题描述
我正在尝试在查询中使用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)'方法,并且该方法无法转换为 存储表达式.
我可以在查询中使用此功能吗?
最简单的解决方法是使用LINQ在之前算出时间限制:
DateTime limit = DateTime.Now.AddMonths(-1);
List<Entities.Subscriber> items = (from s in context.Subscribers
where s.Validated == false && s.ValidationEmailSent == true &&
s.SubscriptionDateTime < limit)
select s).ToList();
或更容易理解的IMO:
var items = context.Subscribers
.Where(s => !s.Validated &&
s.ValidationEmailSent &&
s.SubscriptionDateTime < limit)
.ToList();
在此处使用查询表达式没有任何好处,并且与true
和false
的显式比较是丑陋的IMO(除非您的属性当然是Nullable<bool>
类型).
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?
The simplest fix to this is to work out the time limit once before using LINQ:
DateTime limit = DateTime.Now.AddMonths(-1);
List<Entities.Subscriber> items = (from s in context.Subscribers
where s.Validated == false && s.ValidationEmailSent == true &&
s.SubscriptionDateTime < limit)
select s).ToList();
Or more readably IMO:
var items = context.Subscribers
.Where(s => !s.Validated &&
s.ValidationEmailSent &&
s.SubscriptionDateTime < limit)
.ToList();
There's no benefit in using a query expression here, and explicit comparisons with true
and false
are ugly IMO (unless your properties are of type Nullable<bool>
of course).
这篇关于如何在Linq-to-Entities查询中使用DateTime.AddXXXX函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!