6

In EF 6, if I wanted to select users for instance by distinct last name I could do something like this:

var users = _context.User
            .GroupBy(x => x.LastName)
            .Select(x => x.FirstOrDefault())
            .OrderBy(x => x.LastName)
            .Take(10)
            .ToList();

In EF Core 3.1.6 this very same query gives me the following exception:

System.InvalidOperationException: The LINQ expression '(GroupByShaperExpression:
KeySelector: (u.LastName), 
ElementSelector:(EntityShaperExpression: 
    EntityType: User
    ValueBufferExpression: 
        (ProjectionBindingExpression: EmptyProjectionMember)
    IsNullable: False
)
)
    .FirstOrDefault()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()

Is there any way to use that query without using AsEnumerable (or other alternatives) which would load this entire huge table into memory? The database I use underneath is Microsoft SQL Server 2014 which can handle this kind of query.

0

1 Answer 1

12

This type of queries will probably be supported in EF Core 5 (there for sure are open issues in EF Core GitHub repository).

The workaround in EF Core 3.x is similar to How to select top N rows for each group in a Entity Framework GroupBy with EF 3.1 - (1)use a subquery to select the distinct key values and (2) then join/correlate it with the main query combined with limiting operator (in this case, Take(1)):

var users = _context.User.Select(x => x.LastName).Distinct() // (1)
    .SelectMany(key => _context.User.Where(x => x.LastName == key).Take(1)) // (2)
    // the rest is the same as the origonal
    .OrderBy(x => x.LastName)
    .Take(10)
    .ToList();
2
  • 2
    Isn't it appalling? Even LINQ-to-SQL translates it correctly! The work-around is fancy enough but such restrictions will put off many developers. Well, you know all about it. One drawback worth mentioning is that a projection will still select the entire record in the subquery and only affect the field list of the main query. Unless you're willing to repeat the projection (including the grouping key) in the subquery. Sigh... Aug 11, 2020 at 11:48
  • 1
    @Gert The funny (or sad?) thing is that the join subquery generated by the SelectMany is using ROW_NUMBER() OVER(PARTITION BY ... combined with where row <= 1, which is the exact translation needed for top N items of a group. The distinct part is not needed at all. But what to say about people generating 3 self joins in order to include a single field mapped to the same table :-( They do many good things/improvements over EF6, at the same time very stupid/weird things, and want people to vote "fixing" them as "enhancement" / feature rather than bug fix :-/
    – Ivan Stoev
    Aug 11, 2020 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.