How can i use DateTime.AddXXXX functions in a Linq-to-Entities query?

有些话、适合烂在心里 提交于 2019-12-13 08:36:58

问题


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?


回答1:


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).




回答2:


Jon Skeet has already provided a simple fix, but if you want the DateTime.Now.AddMonths bit to run on the database, try the EntityFunctions.AddMonths method.

This is a more general approach that is especially useful when you cannot replicate the expression cheaply or correctly on the client.




回答3:


You can change your code to:

 DateTime oneMonth = DateTime.Now.AddMonths(-1)
    List<Entities.Subscriber> items = (from s in context.Subscribers
                     where s.Validated == false && s.ValidationEmailSent == true && s.SubscriptionDateTime < oneMonth
                     select s).ToList();

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.



来源:https://stackoverflow.com/questions/7877024/how-can-i-use-datetime-addxxxx-functions-in-a-linq-to-entities-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!