Efcore: System.InvalidOperationException: 'An exception occurred while reading a database value. The expected type was 'System.Int32' but the actual value was of type 'System.Int16'.'

Created on 16 Aug 2018  路  6Comments  路  Source: dotnet/efcore

The following Linq query generates the titled exception.

```C#
from e in es
join d in ds on e.Id equals d.EmployeeId into x
from j in x.DefaultIfEmpty()
select new Holder
{
Name = e.Name,
DeviceId = j.DeviceId //(short?)
}

es and ds are DbSets. 
DeviceId is type of int?.
j.DeviceId is type of short.

If we remove DefaultIfEmpty(), then we don't get the exception.

Please refer to the **Steps to reproduce** for complete source code.

**Exception message:** 

System.InvalidOperationException: 'An exception occurred while reading a database value. The expected type was 'System.Int32' but the actual value was of type 'System.Int16'.'


**Stack trace:**

at Microsoft.EntityFrameworkCore.Metadata.Internal.EntityMaterializerSource.ThrowReadValueExceptionTValue
at Microsoft.EntityFrameworkCore.Storage.Internal.TypedRelationalValueBufferFactory.Create(DbDataReader dataReader)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer) at Microsoft.EntityFrameworkCore.Storage.Internal.NoopExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor1.EnumeratorExceptionInterceptor.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at TestHostForCastException.Program.Main(String[] args) in C:\EFCoreTestBed\Program.cs:line 23

Inner Exception 1:
InvalidCastException: Specified cast is not valid.
```

Steps to reproduce

Repro included at https://github.com/avinash-phaniraj-readify/EFCoreTestBed/tree/CastErrorInProjection

Further technical details

EF Core version: 2.1
Database Provider: EntityFrameworkCore.SqlServerCompact35
Operating system: Windows 10.0.17134
IDE: Visual Studio 2017 15.7.5

closed-fixed customer-reported type-bug

All 6 comments

@smitpatel Thanks for following it up so quickly. Looking forward to 2.2. 馃憤

Re-opening to consider for 2.1.5 patch.

@smitpatel Please create a PR to port this to release/2.1, but don't merge it. Also, please add appropriate quirking--let's discuss if there are issues.

(There is a new process in shiproom and we need to have the final PR to the release branch in order to get approval. Doing this today would be great so we can take this issue tomorrow.)

@smitpatel The branch is now ready for this to be merged.

Confirming that this is now fixed in 2.1.4. Many thanks team.

Was this page helpful?
0 / 5 - 0 ratings