'Query in DB casts to bigint unnecessarily
I have a query in linq that looks like:
IEnumerable<long> ids = Enumerable.Range(1,5).Select(x => (long)x).ToList();
this.tableA.Where(x => ids.Contains(x.id))
.Take(1000)
.ToList();
The resulting query casts each of the values in IEnumerable<long> ids
to bigint and I don't understand why, My tableA Model in my code uses long for the id and the table in the DB uses bigint for the id
This is the query:
SELECT TOP (1000)
[Extent1].[id] AS [id]
FROM [dbo].[tableA] AS [Extent1]
WHERE [Extent1].[id] IN (cast(1 as bigint), cast(2 as bigint), cast(3 as bigint), cast(4 as bigint), cast(5 as bigint))
Anyone knows why this casting happens?
Solution 1:[1]
According to Entity Framework Core Tutorials at Conventions in Entity Framework Core, long is considered and dealt as bigint due to both being a Int64 type. If you want to use sql data type int you should declare your properties as int in c#. This is the case for other ORM's as well.
Solution 2:[2]
If you think simply, It is the direct convertion from SQL to C#. SQL bigint directly convert to System.Int64 in C#.
In C#:
int = System.Int32
long = System.Int64
short = System.Int16
Please check tke SQL server data type mapping documentation: https://docs.microsoft.com/en-us/sql/connect/ado-net/sql-server-data-type-mappings?view=sql-server-ver15
Therefore, you will get long type in the ORM and bigint in the SQL table.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bilal Bin Zia |
| Solution 2 | Shuvra |
