3

Note: This appears to be a different issue from this other question as my problem pertains to Expressions and has nothing to do with NetTopologySuite or Owned types: InvalidCastException after upgrading to EF Core 5.0

I am having a number of unit tests fail after finally updating my project from EF Core 2.2 to EF Core 5.0. All are failing with a variation of:

System.InvalidCastException : Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'Microsoft.EntityFrameworkCore.Query.QueryRootExpression'.

For example, as a follow up to this question of mine: Translating query with GROUP BY and COUNT to Linq

I updated my query to the EF Core 3.0+ example given in the accepted answer, the only change being I am using a defined class in the results instead of an anonymous type:

var countData = await _context.Sale
    .GroupBy(s => s.InternalUser.UserName)
    .Select(g => new SaleCountSummary
    {
        UserName = g.Key,
        InsertCount = g.Sum(s => s.Version == 1 ? 1 : 0),
        UpdateCount = g.Sum(s => s.Version > 1 ? 1 : 0),
    })
    .ToListAsync();

This queries the Sale table to see how many rows each InternalUser has inserted and how many they have updated based on the Version number in the row.

This throws the aforementioned exception when called from a unit test using the InMemoryDatabase, but it translates to SQL and works just fine in my application against an actual SQL Server database.

Valuator
  • 3,262
  • 2
  • 29
  • 53
  • Sounds like you should file a bug report at https://github.com/dotnet/efcore/issues - out of interest, what happens if you change it back to using `Count()` with a predicate? – Ian Kemp Nov 12 '20 at 17:31
  • @IanKemp same error if I go back to the EF Core 2.2 query. – Valuator Nov 12 '20 at 17:32
  • @Valuator, instead of using InMemory store, switch to SQLite in-memory. Looks like this store become less maintained. – Svyatoslav Danyliv Nov 14 '20 at 20:28
  • @SvyatoslavDanyliv, I'd like to and have looked into it in the past but our `DbContext` is too dependent on SQL Server functions for default values ex. `.HasDefaultValueSql("(newid())")` – Valuator Nov 16 '20 at 15:28

0 Answers0