[英]LINQ group by in Entity Framework Core 3.1
我有一个数据库表来连接用户和客户端之间的数据。
db: class UserClientCorporate{
int UserId;
User User;
int ClientCorporateId;
ClientCorporate ClientCorporate;
}
我想查询以获取按userid
分组的ClientCorporates
列表。 我在 LINQ 中遵循了诸如Group by 之类的 Stack Overflow 上的一些示例
这是我的查询:
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());
当我运行这个时,我得到了错误:
失败:Microsoft.AspNetCore.Server.Kestrel[13] 连接 ID“0HLT67LJQA4IP”,请求 ID“0HLT67LJQA4IP:0000000F”:应用程序引发了未处理的异常。 System.InvalidOperationException: 无法翻译 LINQ 表达式“ToList(GroupByShaperExpression: KeySelector: u.UserId, ElementSelector:ProjectionBindingExpression: EmptyProjectionMember)”。 以可翻译的形式重写查询,或通过插入对 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的调用显式切换到客户端评估。 有关详细信息,请参阅https://go.microsoft.com/fwlink/?linkid=2101038 。
如何解决这个问题呢?
解决了 ! 在我做了更多研究之后,似乎 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# 中的代码编写者是客户端。
删除这个.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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.