Linq加入GroupBy和Sum

乔希

我有一个交易表和一个客户表,如下所示:

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)显示错误,表明“ Sum在当前上下文中不存在”。

我也不确定在查询语法中将分组子句放在何处以通过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();
阿舍古鲁

尝试这个。

await _context.SalesTransactions
        .GroupBy(w => w.CustomerId)
        .Select(x => new SalesTransactions() 
        {
            CustomerId = x.Key,
            Amount = x.Sum(w => w.Amount)
        }).ToListAsync();

在此处输入图片说明

在此处输入图片说明

编辑2

await _context.SalesTransactions.Include(x => x.Customer).ToListAsync()
    .GroupBy(w => new { w.CustomerId, w.Customer })
    .Select(x => new SalesTransactions() 
    {
        CustomerId = x.Key.CustomerId,
        Customer = x.Key.Customer,
        Amount = x.Sum(w => w.Amount)
    }).ToListAsync();

在此处输入图片说明

可以从SalesTransaction类中的Customer.Name获取名称。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章