如何解决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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。