efcore
efcore copied to clipboard
Entity with an enum propery type may throw an InvalidCastException when using FromSql
EF assumes that columns are returned from the database in the order it expects. This is not always true especially if using FromSql.
Suppose you have a db schema:
public enum PetType
{
Dog,
Cat
}
public class Pet
{
public int Id { get; set; }
public string Name { get; set; }
public PetType Type { get; set; }
}
public class SampleDb : DbContext
{
public DbSet<Pet> Pets { get; set; }
}
calling db.Pets.FromSql(@"SELECT Id, [Type], [Name] FROM Pet").ToList(); will throw an InvalidCastException. It assumes that the 3rd column is of type PetType (int).
InvalidCastException: Specified cast is not valid.
lambda_method(Closure , Object[] )
Microsoft.Data.Entity.Storage.Internal.RemappingUntypedRelationalValueBufferFactory.Create(DbDataReader dataReader) in RemappingUntypedRelationalValueBufferFactory.cs
_processValuesAction?.Invoke(values);
Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext() in QueryingEnumerable.cs
Current
System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
System.Linq.Enumerable.<SelectManyIterator>d__1`2.MoveNext()
System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
Microsoft.Data.Entity.Query.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext() in LinqOperatorProvider.cs
throw;
System.Linq.AsyncEnumerable.<>c__DisplayClass5`1.<>c__DisplayClass7.<ToAsyncEnumerable>b__2()
System.Threading.Tasks.Task`1.InnerInvoke()
System.Threading.Tasks.Task.Execute()