Efcore: Update from 2.0 to 2.1.1: InvalidCastException when casting to/from enum in query.

Created on 5 Jul 2018  路  3Comments  路  Source: dotnet/efcore

In EF Core 2.0 queries like these would work:
(Status is an enum)

```C#
int status = 1;

context.Employees
.Where(e => (int)e.Status == status)
.ToList();

context.Employees
.Where(e => e.Status == (Status)status)
.ToList();

However, after updating to EF Core 2.1.1 I get the following exception:

Message:
Invalid cast from 'System.Int32' to 'EFCoreTest.Status'.

Stacktrace:
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
at Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter2.Sanitize[T](Object value) at Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter2.<>c__DisplayClass3_02.<SanitizeConverter>b__0(Object v) at Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping.CreateParameter(DbCommand command, String name, Object value, Nullable1 nullable)
at Microsoft.EntityFrameworkCore.Storage.Internal.TypeMappedRelationalParameter.AddDbParameter(DbCommand command, Object value)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalParameterBase.AddDbParameter(DbCommand command, IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.CreateCommand(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntitiesTOut,TIn
at System.Linq.Enumerable.ToListTSource
at EFCoreTest.Program.Main(String[] args) in C:Userskoen.debackerSourcereposEFCoreTestEFCoreTestProgram.cs:line 13

### Steps to reproduce
Project: [EFCoreTest.zip](https://github.com/aspnet/EntityFrameworkCore/files/2165725/EFCoreTest.zip)

```C#
    public class TestContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=EFCoreTest;Trusted_Connection=True;MultipleActiveResultSets=true;");
        }
    }

    public class Employee
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public Status Status { get; set; }
    }

    public enum Status
    {
        Inactive = 0,
        Active = 1
    }
    class Program
    {
        static void Main(string[] args)
        {
            var context = new TestContext();

            int status = 1;

            context.Employees
                .Where(e => (int)e.Status == status)
                .ToList();

            context.Employees
                .Where(e => e.Status == (Status)status)
                .ToList();
        }
    }

Further technical details

EF Core version: 2.1.1
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2017 15.7.4

closed-fixed customer-reported regression type-bug

All 3 comments

Triage: marking this as investigation for patch since the scenario is simple and it is a regression.

This issue has reappeared and the sample program also fails on EF Core 3.1.3. I've attached an
updated solution.
EFCoreTest.zip

@mmjsd I am able to repro this on 3.1.3. It looks like it is fixed by #19128 which will be released in 3.1.4. It's also fixed in EF Core 5.0 preview 3 which is already available.

Was this page helpful?
0 / 5 - 0 ratings