I'm using Entity Framework Core 6. Basically the latest version to date and I'm seeing a significant difference in performance for these 2 blocks of code:
var items = await context.Items.Where(...).ToListAsync();
And:
var sql = context.Items.Where(...).ToQueryString();
var items = await context.Items.FromSqlRaw(sql).ToListAsync();
As a user I'd imagine the first block of code converts into the second one inside the library but apparently something else happens behind the scene. The resulting query has to be the same as all the conditions and everything is identical. Yet block #1 fails with the timeout and block #2 executes super fast and I get results immediately.
What's going on?
UPDATE 1.
My .Where(...) clause looks like this:
.Where(ro => ro.AccountId == accountId &&
(
ro.CustomerEmail == query.Email ||
ro.CustomerEmail1 == query.Email ||
ro.CustomerEmail2 == query.Email
))
UPDATE 2.
This is the SQL that I get from ToQueryString() call (I formatted it for readability):
DECLARE @__account_AccountId_0 nvarchar(200) = N'12345678';
DECLARE @__email_1 nvarchar(200) = N'test@gmail.com';
SELECT [r].* -- all fields
FROM [MyTable] AS [r]
WHERE ([r].[AccountId] = @__account_AccountId_0) AND (
(([r].[CustomerEmail] = @__email_1) OR
([r].[CustomerEmail1] = @__email_1)) OR
([r].[CustomerEmail2] = @__email_1))