【发布时间】:2023-03-30 02:33:01
【问题描述】:
我有如下的交易表和客户表:
public class Customer
{
public string Id{ get; set; }
public string Name { get; set; }
public string Password { get; set; }
}
public class SalesTransaction
{
public int Id { get; set; }
public decimal Amount { get; set; }
public string CustomerId{ get; set; }
}
现在我需要获取每个客户的交易总金额列表,并在列表中显示客户名称和总交易金额
我试过下面的 linq 方法语法
await _context.SalesTransactions
.GroupBy(w=>w.CustomerId)
.OrderByDescending(g=>g.Sum(t=>t.Amount))
.ToListAsync();
但是当我尝试运行它时,我收到以下错误
InvalidOperationException:不支持客户端 GroupBy。
我也试过下面的查询语法
var TransactionSummary = await (from w in _context.WalletTransactions
//join c in _context.Customers
on w.CustomerId equals c.Id
group w by w.CustomerId
into ct
//from c in ct.DefaultIfEmpty()
select new
{
ID=ct.Key,
TransactionAmount=ct.Sum(a=>a.Amount),
// ct.Name
}).ToListAsync();
但 Sum(w.Amount) 显示错误,提示“当前上下文中不存在总和”。
我也不确定在查询语法中的何处放置分组子句以实现分组 Customer.Id 字段的结果。
请注意,我注释掉的行是我希望添加的子句,但不确定在何处以及如何正确添加它们
我希望找到正确的方法来解决这个问题。
谢谢
找到的解决方案: 感谢@Asherguru 的回答
我只需要稍微修改一下就可以达到预期的结果
以下工作
var transactions= (await _context.SalesTransactions.Include(x => x.Sender).ToListAsync())
.GroupBy(w => new { w.CustomerId, w.Sender })
.Select(x => new
{
CustomerID= x.Key.CustomerId,
x.Key.Customer,
Amount = x.Sum(w => w.Amount)
}).ToList();
【问题讨论】:
标签: c# linq linq-to-sql entity-framework-core left-join