Nev*_*ynh 0 c# linq linq-to-entities entity-framework
我想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();
Run Code Online (Sandbox Code Playgroud)
但我收到一个错误:
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();
Run Code Online (Sandbox Code Playgroud)
或者更可读IMO:
var items = context.Subscribers
.Where(s => !s.Validated &&
s.ValidationEmailSent &&
s.SubscriptionDateTime < limit)
.ToList();
Run Code Online (Sandbox Code Playgroud)
在这里使用查询表达式没有任何好处,并且与IMO进行显式比较true并且false是丑陋的IMO(除非您的属性Nullable<bool>当然是类型).
Jon Skeet已经提供了一个简单的修复,但如果你想DateTime.Now.AddMonths在数据库上运行该位,请尝试使用该EntityFunctions.AddMonths方法.
这是一种更通用的方法,当您无法在客户端上以低成本或正确方式复制表达式时,此方法尤其有用.