Unnecessary conversion to bigint
Asked Answered
L

2

14

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?

Lonnylonslesaunier answered 8/2, 2017 at 6:51 Comment(0)
W
6

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.

Wrand answered 8/2, 2017 at 7:10 Comment(0)
P
-2

Not really sure what you're asking for here but..

Change your long to int and the query should make you an int instead of bigint.

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

Long is the equivalent of bigint. You can read more here: What is the equivalent of bigint in C#?

Piraeus answered 8/2, 2017 at 7:0 Comment(1)
I can't do this.. I need long typeLonnylonslesaunier

© 2022 - 2024 — McMap. All rights reserved.