question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

InvalidCastException when using unmapped parameterized enum

See original GitHub issue

The query below to filter by the day of week of a DateTime throws an InvalidCastException.

var dayOfWeek = DayOfWeek.Monday;
var mondayTransactions = await _context.Transactions
    .Where(t => t.Date.DayOfWeek == dayOfWeek)
    .ToListAsync();

And this other query correctly translates to SQL using a hardcoded day of week.

var mondayTransactions = await _context.Transactions
    .Where(t => t.Date.DayOfWeek == DayOfWeek.Monday)
    .ToListAsync();

The exception thrown by the first query:

System.InvalidCastException: Can't write CLR type System.DayOfWeek with handler type Int32Handler
   at lambda_method(Closure , NpgsqlTypeHandler , Object , NpgsqlLengthCache& , NpgsqlParameter )
   at Npgsql.TypeHandling.NpgsqlSimpleTypeHandler`1.ValidateObjectAndGetLength(Object value, NpgsqlLengthCache& lengthCache, NpgsqlParameter parameter)
   at Npgsql.NpgsqlParameter.ValidateAndGetLength()
   at Npgsql.NpgsqlCommand.ValidateParameters(ConnectorTypeMapper typeMapper)
   at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)

Luckily there are only seven days in a week, so I’m working around this issue by using an extension method like this

public static IQueryable<Transaction> FilterByDayOfWeek(this IQueryable<Transaction> transactions, DayOfWeek dayOfWeek)
{
    return dayOfWeek switch
    {
        DayOfWeek.Monday => transactions.Where(t => t.Date.DayOfWeek == DayOfWeek.Monday),
        DayOfWeek.Tuesday => transactions.Where(t => t.Date.DayOfWeek == DayOfWeek.Tuesday),
        ...
    };
}

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:1
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

4reactions
rojicommented, Feb 20, 2020

For now, as a workaround, you can cast the parameterized enum to an int before using it in your LINQ query:

var dayOfWeek = (int)DayOfWeek.Monday;
var mondayTransactions = await _context.Transactions
    .Where(t => (int)t.Date.DayOfWeek == dayOfWeek)
    .ToListAsync();
1reaction
yyjdeletecommented, Aug 1, 2020

@zakeryooo Try this? var shops = ctx.Shops.Where(s => s.Regions.Contains((Region)(object)region.ToString())).ToList();

Read more comments on GitHub >

github_iconTop Results From Across the Web

ExpressMapper - mapping/cloning enums
My problem comes down to mapping Enums and the fact that enums should not be cast directly, as this will generate an InvalidCastException....
Read more >
How to use Enums when using Entity Framework Core with ...
Our first option was to model the enum as a separate table and use an unmapped property to cast it to an enum,...
Read more >
Enumeration types - C# reference
IsDefined method to determine whether an enumeration type contains an enum member with the certain associated value. For any enumeration type, ...
Read more >
TypeScript: Handbook - Enums
String enums allow you to give a meaningful and readable value when your code runs, independent of the name of the enum member...
Read more >
Extending Enums in Java
When we want to extend a Java class, we typically create a subclass. In Java, enums are classes as well. In this section,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found