0

How to convert following sql query to Linq,

 Select F1, F2
   From [Table]
  Where Convert(Varchar(10), [OnDate], 103) = '12/08/2019'  
7
  • The SQL query is wrong to begin with. Use the correct types instead of localized strings. This query should be WHERE OnDate=@someDate or WHERE cast(onDate as date)=@someDate if you want to match only on the date part. SQL Server is smart enough to convert that to a range query. Once you fix that bug, LINQ is a simple .Where(row=>row.OnDate=someDate) Commented Sep 10, 2019 at 9:37
  • check modified query Commented Sep 10, 2019 at 9:38
  • There's no difference in the query, it's still bad. A correct query in LINQ would be someContext.ThatTable.Where(row=>row.OnDate=someDate), with a Select if only a couple of fields are required. LINQ would generate a parameterized query for this with the date value passed as a parameter Commented Sep 10, 2019 at 9:41
  • @PanagiotisKanavos "SQL Server is smart enough to convert that to a range query" got any evidence for that? --- ah, now I see, thanks. The execution plan shows 'StartRange ScanType="GT"' Commented Sep 10, 2019 at 9:45
  • @Caramiriel check the execution plan and a lot of relevant of SO questions. You'll see that an Index Seek is used instead of a scan Commented Sep 10, 2019 at 9:46

1 Answer 1

1

The correct way to filter datetime values by date only is to use cast( ... as date) :

declare @myDate date='20190812'

Select F1, F2
From [Table]
Where cast([OnDate] as date)=@myDate

This avoids any parsing and localization errors and takes advantage of indexes that cover the OnDate column. Without it the server would have to scan the entire table to convert the dates into strings before comparing them.

This is due to the dynamic seek optimizations introduced at least as far back as SQL Server 2008 R2.

LINQ by itself doesn't query databases. It's a query language that gets translated by an ORM into actual SQL statements. Writing the equivalent of cast( ... as date) depends on the ORM.

In LINQ to SQL, calling DateTime.Date generates a cast( as date) :

var data = context.MyTable.Where(row=>row.OnDate.Date=someDate.Date);

or

var data = from row in contect.MyTable
           where row.OnDate.Date=someDate.Date
           select row;

EF doesn't recognize this and requires the DbFunctions.TruncateTime call :

var data = context.MyTable.Where(row=>DbFunctions.TruncateTime(row.OnDate)=someDate.Date);

EF Core once again recognizes DateTime.Date :

var data = context.MyTable.Where(row=>row.OnDate.Date=someDate.Date);
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.