Linq Sum没有分组依据

时间:2019-08-08 17:39:35

标签: mysql asp.net linq core

Linq的新手需要了解如何做一些基本的事情,例如简单的查询,将金额列求和并将其作为类型返回。

这是我要转换的查询。

  SELECT
      SUM( trans_trades.amount )
  FROM
      trans_trades
  INNER JOIN trans_series ON trans_series.id = trans_trades.series_id 
  WHERE
    trans_trades.series_id  IN (
    17,
    18)

我的视图模型:

    public class TotalTransRaise
    {
        public decimal Total { get; set; }

    }

方法:

        public TotalTransRaise GetTotalTransRaise()
        {
            _context = new MySQLDatabaseContext();

            var result = (from t1 in _context.TradesSeries
                join t2 in _context.TradesTrades on t1.Id equals t2.SeriesId
                where myInClause.Contains(t2.SeriesId)
                select new TotalTransRaise
                {

                    Total = (decimal) t2.Amount //this gives an error because Amount represents all the amounts because I can't apply .Sum() here to make it one summed aggregate, so the method thinks I should be casting TotalTransRaise as a list.   

                });

            return result;

        }

1 个答案:

答案 0 :(得分:0)

我通过将方法更改为来修复它:

        public TotalTransRaise GetTotalTransRaise()
        {
            _context = new MySQLDatabaseContext();

            var result = _context.TradesSeries
                .Join(_context.TradesTrades, t1 => t1.Id, t2 => t2.SeriesId, (t1, t2) => new {t1, t2})
                .Where(t => myInClause.Contains(t.t2.SeriesId))
                .GroupBy(s => s.t1.Active)
                .Select(g => 
                    new TotalTransRaise
                    {
                        Total = g.Sum(x => x.t2.Amount)
                    }
                ).FirstOrDefault();
            return result;
        }