2

Edmx file has

<Property Name="SomePrimaryKeyID" Type="bigint" />

Corresponding object's property is

<Property Type="Int64" Name="SomePrimaryKeyID" Nullable="false" />

Query:

  long[] ids = new long[]{1234567,1234568};
  var results = context.SomeEntities.Where(x=> ids.Contains(x.SomePrimaryKeyID)).ToList();

When I use contains, EF generated query has explicit casting such as

... WHERE SomePrimaryKeyID IN (CAST (1234567 AS BIGINT),CAST (1234568 AS BIGINT))

Since long corresponds to bigint, I don't see a need for cast. Is there a way I can avoid this cast?

Lokeshwer
  • 1,139
  • 1
  • 9
  • 14

1 Answers1

1

For literal integral values the default type in the SQL Server is int. Because of that in your example the literal values would have to be always cast (they would be of type 'int' if there was no explicit cast) to match the type of SomePrimaryKeyID (which is big int). If the explicit case was missing Sql Server would have to do an implicit cast which actually might be more expensive since it would have to first reason about the type of the SomePrimaryKeyID to know what to cast the literal numbers to.

Pawel
  • 31,342
  • 4
  • 73
  • 104
  • How are these queries different 1. "select * from SomeEntity where SomePrimaryKeyID in (9223372036854775807)" 2. "select * from SomeEntity where SomePrimaryKeyID in (CAST(9223372036854775807 AS BIGINT))" – Lokeshwer Sep 27 '13 at 07:46
  • I suppose without CAST Sql Server is inferring that the type of the literal has to be bigint because of the type of the column (or it treats the literal as bigint because it does not fit in int or both). In general - why does the cast bother you? – Pawel Sep 27 '13 at 21:19
  • @pawel the casting is important because it results in a non-parameterised query which can adversely affect performance because each query gets a new query plan (and can't be reused unless with exactly the same values) – Andrew May 10 '16 at 00:47