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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...