score:2

Although EF Core 2.1 introduced improvements to LINQ GroupBy translation, the implementation is still far from perfect and produces exceptions in many scenarios due to invalid SQL generation. Your scenario is just one of them and is not working even with the recent at this time EF Core 2.1.1 bits.

The first thing you should do is to submit it to the EF Core issue tracker, so they know and fix it when possible.

The problem seems to be related to the key property aliasing (it also doesn't work if you use the "normal" .GroupBy(e => e.TypeId).OrderBy(g => g.Key)). The current workaround I've found is to use anonymous type key having the same property name(s) as the source(s):

_context.MyTable
    .GroupBy(e => new { e.TypeId })
    .OrderBy(g => g.Key.TypeId)
    .Select(g => g.Count()) 

Related Articles