2

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)
4
  • 3
    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. Commented Jun 22, 2022 at 13:34
  • 3
    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. Commented Jun 22, 2022 at 14:06
  • @SvyatoslavDanyliv Your advice to compare dates by range rather than equality is interesting. Why is it better? Commented Jul 11, 2024 at 13:54
  • 1
    @lonix, because range comparison uses Database Indexes, if they exists for sure. If you truncate to date they will be disabled and you will have table scan. I saw that for several casess SQL have optimizations for CONVERT(date, DateColumn) but I wouldn't hope for it. Commented Jul 11, 2024 at 16:04

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.