使用SUM和Group By对两个表进行Linq查询



我有两个表

回复

|ReplyID     |ReplyText | QuestionID | CreatedOn  |
|1           |xxxxxx    |1           | 01/01/2016 |
|2           |yyyyyy    |2           | 02/01/2016 |
|3           |zzzzzz    |3           | 03/01/2015 |

和投票

|ReplyID     |VoteValue |UserId   |
|1           |1         |1        |
|1           |1         |2        |
|2           |-1        |3        |
|3           |1         |4        |

我正试图将ReplyId上的两个表与作为控制器参数获得的id值连接起来。

这是我正在使用的linq查询:

Replies = from r in db.Replies
          join v in db.Votes on r.ReplyID equals v.ReplyId
          where r.QuestionId == id
          orderby r.CreatedOn descending
          group v by v.ReplyId into g
          select g.Key

其中Replies是

public IGrouping<Reply, Vote> Replies { get; set; }

我有这个错误:

无法将类型"System.Linq.IQUERABLE"隐式转换为System.LinqIGrouping

我无法从这里出发。我需要在Votes表中求和(VoteValues),并将其与Replies表连接以获得所有列值。如有任何帮助,我们将不胜感激。

您可以使用组联接:

var result= from r in db.Replies
            join v in db.Votes on r.ReplyID equals v.ReplyId into votes
            where r.QuestionId == id
            orderby r.CreatedOn descending
            select new {Reply=r, Votes=votes.Sum(v=>v.VoteValue)};

根据您的描述,您需要从Reply中获得所有列以及所有投票的总和。通过这种方式,您可以使用匿名来投影查询,以保存Reply实例和所需的总和。现在,您可能需要将投影保存为已知类型,因为您需要将此查询的结果传递给控制器。在这种情况下,我建议创建一个自定义类(也称为DTO):

public class ReplySum
{ 
  public Reply Reply {get;set;}
  public int Votes{get;set;}
}

现在你可以这样投影你的查询:

IQueryable<ReplySum> query =from r in db.Replies
                            join v in db.Votes on r.ReplyID equals v.ReplyId into votes
                            where r.QuestionId == id
                            orderby r.CreatedOn descending
                            select new ReplySum{Reply=r, Votes=votes.Sum(v=>v.VoteValue)};

你需要考虑的另一件事是在将结果传递给你的视图之前实现你的查询:

var result=query.ToList();//Or ToArray

使用lambda表达式可以简化查询:

var result = db.Replies.Select(i => new
                    {
                        VoteCount = i.Votes.Sum(j => j.VoteValue),
                        Reply = i
                    })
                    .ToList();

最新更新