EF Core按栏划分

问题描述

在EF 6中,如果我想通过不同的姓氏来选择用户,例如,我可以这样做:

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

在EF Core 3.1.6中,这个非常相同的查询给了我以下异常:

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()

是否可以使用不使用AsEnumerable(或其他替代方法)的查询来将整个庞大表加载到内存中?我在下面使用的数据库是Microsoft sql Server 2014,可以处理这种查询

解决方法

EF Core 5(在EF Core GitHub存储库中肯定存在未解决的问题)可能会支持这种类型的查询。

EF Core 3.x中的解决方法类似于How to select top N rows for each group in a Entity Framework GroupBy with EF 3.1-(1)使用子查询选择不同的键值,然后(2)然后将其与主查询结合起来/关联,并与限制运算符(在这种情况下,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();