33
votes

This is my code:

 return Newsletterctx.Subscribers.Count(o =>
     o.Validated == false &&
     o.ValidationEmailSent == true &&
     o.SubscriptionDateTime.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.

4

4 Answers

45
votes

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);
41
votes

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);
2
votes

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

0
votes

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.