0

I am migrating my .Net 6 Project from Entity framework 6 to Entity Framework Core and I need to replace the following code. How do I replace this Entity Framework 6 Sql TruncateTime Function with one that works with EF Core.

var result = db.Tickets
               .Where(x => DbFunctions.TruncateTime(x.DateTimeCreated) == statCalcDefinitionDateTime.Date)
BoMerican
  • 118
  • 10
  • 2
    If you care about indexes, you should not do such comparison. `.Where(x => x.DateTimeCreated >= statCalcDefinitionDateTime.Date && x.DateTimeCreated < statCalcDefinitionDateTime.Date.AddDays(1))` should be enough. – Svyatoslav Danyliv Jun 22 '22 at 13:34
  • 2
    Anyway, EF Core has translation of `x.DateTimeCreated.Date` to `CONVERT(date, @dateTime)`, so just replace `DbFunctions.TruncateTime(x.DateTimeCreated)` with `x.DateTimeCreated.Date` but I recommend to use my first approach. – Svyatoslav Danyliv Jun 22 '22 at 14:06

1 Answers1

1

As Svyatoslav Danyliv Said in the comments. Entity framework core now supports "DateTime.Date" so there is no longer a need for the "dbFunctions.TruncateTime()" function.

Svyatoslav Danyliv also suggested I used a range in my where statement instead of the date, and I would agree. Blow is the new Entity Framework Core way of "DBFunctions.TruncateTime()"

var result = db.Tickets
               .Where(x => x.DateTimeCreated.Date == statCalcDefinitionDateTime.Date)

Or alternatively you can use a date range

var result = db.Tickets
               .Where(x => 
                      x.DateTimeCreated >= statCalcDefinitionDateTime.Date && 
                      x.DateTimeCreated < statCalcDefinitionDateTime.Date.AddDays(1))

NOTE: I also found the same solution HERE

BoMerican
  • 118
  • 10