我目前有这个代码:
foreach (var newsToPolitician in news.NewsToPoliticians)
{
var politician = newsToPolitician.Politician;
var votes = (from s in db.Scores
where o.IDPolitician == politician.IDPolitician
&& o.IDNews == IDNews
group o by o.IDAtribute
into g
select new{
Atribute= g.Key,
TotalScore= g.Sum(x => x.Score)
}).ToList();
}
它工作正常,但我想避免foreach
循环对我的数据库进行多次查询。我的表Scores
如下所示:
IDScore | IDNews | IDUser | IDPolitician | IDAtribute | Score
1 40 1010 35 1 1
2 40 1010 35 2 -1
3 40 1002 35 1 1
4 40 1002 35 2 1
5 40 1002 40 1 -1
...
我的目标是汇总新闻中所有政客的所有分数。一条新闻最多可以有 7 个政客。在一个循环
中调用我的数据库多达七次是否很昂贵。foreach
我知道这不是最佳实践,所以我很感兴趣有没有办法在这种特殊情况下避免它并调用数据库然后在服务器端处理它?