Error when passing AddDays on Lambda expression

3

In this lambda, it 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 can not be translated into a store expression.

How do I resolve this?

    
asked by anonymous 06.05.2014 / 02:13

1 answer

5

Use EntityFunctions DbFunctions for such expression: / p>

Difference is that DbFunctions is in System.Data.Entity.DbFunctions and is for version 6+ of Entity Framework , below use EntityFunctions that 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:

06.05.2014 / 02:40