gpt4 book ai didi

c# - Entity Framework Core 3.1 中的 LINQ group by

转载 作者:行者123 更新时间:2023-12-03 14:54:32 28 4
gpt4 key购买 nike

我有一个数据库表来连接用户和客户端之间的数据。

db: class UserClientCorporate{
int UserId;
User User;
int ClientCorporateId;
ClientCorporate ClientCorporate;
}

我想查询以获取 ClientCorporates 的列表按 userid 分组.我在 Stack Overflow 上遵循了一些示例,例如 Group by in LINQ

这是我的查询:
var data3 = from db in _context.UserClientCorporate
group db.ClientCorporateId by db.UserId into g
select new { UserId = g.Key, Clients = g.ToList() };

return Ok(await data3.ToListAsync());

当我运行这个时,我得到了错误:

fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HLT67LJQA4IP", Request id "0HLT67LJQA4IP:0000000F": An unhandled exception was thrown by the application. System.InvalidOperationException: The LINQ expression 'ToList(GroupByShaperExpression: KeySelector: u.UserId, ElementSelector:ProjectionBindingExpression: EmptyProjectionMember )' 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(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.



如何解决这个问题呢?

解决了 !
在我做了更多研究之后,似乎 EF Core 在数据库服务器上执行此查询有限制。所以我需要先获取数据并在我的 dotnet 服务器(客户端)上进行处理。

这里是
var data = await _context.UserClientCorporate.Include(x => x.User).Include( x => x.ClientCorporate).
var res2 = from db in data
group db by db.UserId into g
select new {UserId = g.Key, Clients = g};

最佳答案

.netcore 3.1 不支持客户端 GroupBy
您可以像这样简单地编写查询:

var data3 = __context.UserClientCorporate.ToList().GroupBy(x => x.UserId);
C# 中的代码编写者是客户端。

关于c# - Entity Framework Core 3.1 中的 LINQ group by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60002713/

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