Compares Datetime field in a lambda only part Date

Asked

Viewed 2,820 times

6

In this lambda, result will almost always be null, because I gave a Getdate() straight at the bank and when this happens, I record Date and Time. How do I make this lambda pass only Data and compare with Datetime.Now only the date? I tried to use some features of C# in lambda and did not accept.

var resultado = db.T_PDV
                .Where(a => a.DataCadastro == DateTime.Now)
                .Select(i => new { i.CNPJ})
                .ToList();
  • Pnet this is duplicate: http://answall.com/questions/14857/erro-ao-passar-adddays-expression-lambda/14862#14862 look I already answered this!

  • 2

    It is not duplicate, Harry. Because here I would like to know how I pass only the Date field without the hour part. There speaks of something else, although with date fields.

  • 1

    All right then, but, let’s see how the community will understand this... by me all right, and the answer was given!

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 the Entity Framework, below use Entityfunctions who is in System.Data.Objects.EntityFunctions

In the specific case use DbFunctions.TruncateTime or EntityFunctions.TruncateTime depending on the version of Entity Framework for it to leave only the value of Date. Also in your variable you put the value of Date equal var dta = DateTime.Now.Date; also bringing only Date without time.

var dta = DateTime.Now.Date;    
var resultado = db.T_PDV.Where(a => DbFunctions.TruncateTime(a.DataCadastro) == dta)
                .Select(i => new { i.CNPJ})
                .ToList();

var dta = DateTime.Now.Date;    
var resultado = db.T_PDV.Where(a => EntityFunctions.TruncateTime(a.DataCadastro) == dta)
                    .Select(i => new { i.CNPJ})
                    .ToList();

In that link, has a very similar but using another method. This link server with reference item.

  • Harry, I tried to add the namespace of this Dbfunction method and I can’t. I just have System.Data.Entity and in this namespace I don’t have Dbfunction. I used Entityfunction and it turns out it’s obsolete

  • It wasn’t that. It’s just that I got the first using suggested by him and didn’t have Dbfunctions. I used this using and it worked: using System.Data.Objects;

Browser other questions tagged

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