gpt4 book ai didi

c# - EF Core 按列不同

转载 作者:行者123 更新时间:2023-12-04 00:54:51 24 4
gpt4 key购买 nike

在 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 存储库中肯定存在 Unresolved 问题)。
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();

关于c# - EF Core 按列不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63356777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com