Sunday, December 29, 2024

EF Core 9.0: Introducing EF.Parameter(T)

In this post, let's have a look EF.Parameter<T>(T) method that was introduced with EF 9.0.

Consider the following simple LINQ query.
async Task<List<Employee>> GetEmployees(int employeeId)
{
    return await context.Employees
        .Where(e => e.Id == employeeId && e.IsActive == true)
        .ToListAsync();
}
This would generate a SQL query as follows.
--Executed DbCommand (24ms) [Parameters=[@__employeeId_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
SELECT [e].[Id], [e].[IsActive]
FROM [Employees] AS [e]
WHERE [e].[Id] = @__employeeId_0 AND [e].[IsActive] = CAST(AS bit)
Here you can see the employeeId is parameterized, and IsActive is a constant. When a constant is being used database engine can cache the query resulting a more efficient query.

However if for some reason you want to parameterize the value, you can use EF.Parameter<T>(T).
async Task<List<Employee>> GetEmployees(int employeeId)
{
    return await context.Employees
        .Where(e => e.Id == employeeId && e.IsActive == EF.Parameter(true))
        .ToListAsync();
}
This would generate a SQL query as follows.
--Executed DbCommand (26ms) [Parameters=[@__employeeId_0='?' (DbType = Int32), @__p_1='?' (DbType = Boolean)], CommandType='Text', CommandTimeout='30']
SELECT [e].[Id], [e].[IsActive]
FROM [Employees] AS [e]
WHERE [e].[Id] = @__employeeId_0 AND [e].[IsActive] = @__p_1
While we are on this topic, EF Core 8.0.2 introduced EF.Constant<T>(T) method which forces EF to use a constant even if a parameter would be used by default.
async Task<List<Employee>> GetEmployees(int employeeId)
{
    return await context.Employees
        .Where(e => e.Id == EF.Constant(employeeId) && e.IsActive == EF.Parameter(true))
        .ToListAsync();
}
And this would generate a SQL query as follows.
--Executed DbCommand (18ms) [Parameters=[@__p_1='?' (DbType = Boolean)], CommandType='Text', CommandTimeout='30']
SELECT [e].[Id], [e].[IsActive]
FROM [Employees] AS [e]
WHERE [e].[Id] = 10 AND [e].[IsActive] = @__p_1
Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment