我有一个数据库表,用于在用户和客户端之间连接数据。
db: class UserClientCorporate{
int UserId;
User User;
int ClientCorporateId;
ClientCorporate ClientCorporate;
}
我想查询以ClientCorporates
分组的列表userid
。我在LINQ上遵循了一些关于Stack Overflow的示例,例如Group by
这是我的查询:
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};
删除此.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());
仍然失败失败失败:Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware [1]执行请求时发生未处理的异常。System.InvalidOperationException:通过'RelationalProjectionBindingExpressionVisitor'处理LINQ表达式'GroupByShaperExpression:KeySelector:u.UserId,ElementSelector:ProjectionBindingExpression:EmptyProjectionMember'失败。这可能表示EF Core中存在错误或限制。有关更多详细信息,请参见go.microsoft.com/fwlink/?linkid=2101433。
随着我进行更多的研究,该查询在EF Core中不可行,因此我先获取数据,然后再使用此LINQ查询进行处理。而且有效。
是的,你是对的。这是因为大多数数据库引擎都需要将聚合器功能应用于分组的数据,或者像MySQL那样将分组中的第一行返回。这与IEnumerable group by的行为完全不同。