Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unnecessary conversion to bigint

I have employee table with bigint primary key field in database and entity data model with database first approach. Employee class have this structure

public partial class Employee
{
     public long Emp_No { get; set; }
     public string Name { get; set; }
     public string Family { get; set; }
     ...
}

I write this basic query with Entity Framework

List<long> ids = new List<long>() {1,2,3,4,5,6}
database.Employees.Where(q => ids.Contain(q.Emp_No)).ToList();

It Generate query as the following:

SELECT 
    [Extent1].[Emp_No] AS [Emp_No], 
    [Extent1].[Name] AS [Name], 
    [Extent1].[Family] AS [Family], 
    ...
    FROM [dbo].[Employee] AS [Extent1]
    WHERE [Extent1].[Emp_No] IN (cast(0 as bigint), 
                                 cast(1 as bigint), 
                                 cast(2 as bigint), 
                                 cast(3 as bigint), 
                                 cast(4 as bigint), 
                                 cast(5 as bigint), 
                                 cast(6 as bigint))

As you can see there is unnecessary cast to bigint in query while both type of Emp_No and ids array are long, It causes bad execution times specially whenever ids array has many elements.

How can I remove this redundant cast?

like image 447
Vahid Jafari Avatar asked Feb 08 '17 06:02

Vahid Jafari


1 Answers

There is virtually no cost in the conversion cast(0 as bigint) and because Emp_No is also a bigint if you did not have the cast there the int would still need to be promoted to a bigint to be able to do the IN comparision so the cast would still happen, just behind the scenes.

Run the non cast version of the query yourself in management studio and get the actual execution plan and you will still see the conversion in the query plan.

like image 189
Scott Chamberlain Avatar answered Oct 06 '22 02:10

Scott Chamberlain