LINQ 在 Entity Framework Core 3.1 中分组

LINQ group by in Entity Framework Core 3.1

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

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

我想查询以获取按 userid 分组的 ClientCorporates 的列表。我在 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};

删除此 .tolist() :

var data3 = from db in _context.UserClientCorporate
            group db.ClientCorporateId by db.UserId into g
            select new { UserId = g.Key, Clients = g };

return Ok(await data3.ToListAsync());

.net core 3.1 不支持客户端 GroupBy

您可以像这样简单地编写您的查询:

var data3 = __context.UserClientCorporate.ToList().GroupBy(x => x.UserId);

用 C# 编写的代码是客户端。