2010-08-20 12 views
21

Este es mi código:LINQ a Entidades con método AddMonth

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

consigo este error:

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

Respuesta

34

Tal vez se puede cambiar la fecha para poner a prueba contra su lugar:

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

En este caso, arroja una excepción al declarar la variable testDate: System.NullReferenceException: 'Referencia de objeto no establecida en una instancia de un objeto.' CS $ <> 8__locals0 era nulo. –

+0

@ İlkinElimov Sí, si la secuencia contiene referencias nulas, eso podría suceder. Puedes arreglar eso filtrándolos primero con '.Subscribers.Where (o => o! = Null) .Count (o => ...' –

29

Puede usar SqlFunctions classvar;

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

No he visto SqlFunctions antes, cosas interesantes. –

+1

¡Bonito! Salvó mi día. –

+0

Trabajó para mí también Gracias whitestream! – realPT

0

usted tiene que utilizar la fecha y hora fuera de la solicitud porque usted está en el LINQ a las entidades que no usan Biblioteca System.DateTime.

Si desea utilizar una fecha fija la puede definir fuera la solicitud como

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