When using EF Core with SQL Server for query, the generated SQL uses DECLARE variables.
That changes the execution plan to use a different index altogether.
For example - this is my code:
Set<Order>().Where(x => x.DueDate >= fromDate && x.DueDate <= toDate).ToList()
where Order is an entity with indexes on ID column (IX_ID) and index on DueDate column (IX_DUEDATE).
EF Core generates a query:
DECLARE @__fromDate_1 datetime2 = '2023-11-23T00:00:00.0000000';
DECLARE @__toDate_2 datetime2 = '2023-11-28T00:00:00.0000000';
SELECT *
FROM [dbo].[Orders] AS [o]
WHERE [o].[DueDate] >= @__fromDate_1 AND [o].[Due] <= @__toDate_2
This does an INDEX SCAN on IX_ID (index on ID).
The execution plan of the above is very different from say a query like
SELECT *
FROM dbo.Orders o
WHERE o.DueDate BETWEEN '2023-11-23' AND '2023-11-28';
This does an INDEX SEEK on the index IX_DUEDATE.
How can I get EF Core to generate variables inline instead of declaring them separately?
I have tried generating execution plans of the actual SQL query that I wanted and the SQL generated by EF Core. The execution plans are different.
The execution plan of the desired query results in INDEX SEEK on an INDEX.
The execution plan of the EF Core query results in INDEX SCAN on the primary key.