开发者

LINQ to Entities with AddMonth method

This is my code:

 return Newsletterctx.Subscribers.Count(o =>
     o.Validated == false &&
     o.ValidationEmailSent == true &&
     o.Subscript开发者_运维问答ionDateTime.AddMonths(1) < DateTime.Now);

I get this error:

LINQ to Entities does not recognize the method 'System.DateTime AddMonths(Int32)' method, and this method cannot be translated into a store expression.


You can use SqlFunctions classvar;

 today =  DateTime.Now; return Newsletterctx.Subscribers.Count(o =>
 o.Validated == false &&
 o.ValidationEmailSent == true &&
 SqlFunctions.DateAdd("month",1,o.SubscriptionDateTime) <today);


Perhaps you can shift the date to test against instead:

DateTime testDate = DateTime.Now.AddMonths(-1);
return Newsletterctx.Subscribers.Count
            (o => o.Validated == false 
             && o.ValidationEmailSent == true 
             && o.SubscriptionDateTime < testDate);


You have to use the Datetime outside the request because you are in the LINQ TO ENTITIES that don't use System.Datetime Library.

If you wish to use a fix date the you can define it outside the request as

DateTime compareDate = DateTime.Now.AddMonths(x);


Now, EntityFramework, Version=6 above, you can jus use System.Data.Entity.DbFunctions

return Newsletterctx.Subscribers.Count(o =>
 o.Validated == false &&
 o.ValidationEmailSent == true &&
  DbFunctions.AddMonths(o.SubscriptionDateTime,1) < DateTime.Now);

However, in this case, use the temp variable testDate that answered by Fredrik Mörk uses less resources.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜