Error while passing Adddays in Lambda expression

Asked

Viewed 611 times

3

In this lambda, gives me the error below, when it enters the IF:

var resultado = webDB.T_ControleColetor
                            .Where(cn => cn.CNPJ == cnpj)
                            .Where(dt => dt.DataControle == DateTime.Now.AddDays(-1))
                            .Select(x => x.DataControle);

            if(resultado.Count() > 0)
            {
                result = 1;
            }

LINQ to Entities does not recognize the method 'System.Datetime Adddays(Double)' method, and this method cannot be Translated into a store.

How do I fix it?

1 answer

6


Utilize Entityfunctions or Dbfunctions for such an expression:

Difference is Dbfunctions is in System.Data.Entity.DbFunctions and is for version 6+ of Entity Framework, below use Entityfunctions who are in System.Data.Objects.EntityFunctions

With Entityfunctions

DateTime data = DateTime.Now.Date;
var resultado = webDB.T_ControleColetor
                            .Where(cn => cn.CNPJ == cnpj)
                            .Where(dt => dt.DataControle == EntityFunctions.AddDays(Data, - 1))
                            .Select(x => x.DataControle);

            if(resultado.Count() > 0)
            {
                result = 1;
            }

With Dbfunctions

DateTime data = DateTime.Now.Date;
var resultado = webDB.T_ControleColetor
                            .Where(cn => cn.CNPJ == cnpj)
                            .Where(dt => dt.DataControle == DbFunctions.AddDays(Data, - 1))
                            .Select(x => x.DataControle);

            if(resultado.Count() > 0)
            {
                result = 1;
            }

Reference:

  • I did it last night with Entityfunctions, but I’ll consider your answer, Fccdias.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.