c# - LINQ group by in Entity Framework Core 3.1
问题描述
I have a database table to connect data between user and clients.
db: class UserClientCorporate{
int UserId;
User User;
int ClientCorporateId;
ClientCorporate ClientCorporate;
}
I want to query to get list of ClientCorporates
grouped by userid
. I have follow some example on Stack Overflow like Group by in LINQ
and here is my query:
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());
When I run this, I got error:
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.
How to solve this problem?
SOLVED ! After I did more research it seems EF Core has limitation doing this query on database server. so I need to get the data first and processed it on my dotnet server (client).
Here is the
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};
解决方案
Client side GroupBy is not supported in .netcore 3.1
You may write your query as simple as this:
var data3 = __context.UserClientCorporate.ToList().GroupBy(x => x.UserId);
Code writter in C# is client side.
推荐阅读
- python - 找到字典中的元素(包含在列表中)后如何停止列表中的 for 循环
- node.js - 使用 Node.js 实现推送通知
- kalman-filter - 验证卡尔曼滤波器的答案
- python - 如何在 wx.dataview.TreeListCtrl 中骑空方块
- javascript - 覆盖react datepicker popper className的样式
- c# - RadGrid 中的超链接 onclick
- java - 将窗口最小化到 JavaFX 应用程序时图像消失
- angular - 如何在 ng2-table 组件中使用 i18n?
- r - 如何让 R Shiny 标题面板从服务器中提取文本?
- c++ - OpenMP 不会运行多个线程