[英]linq query to take aggregate and normal column in c# mvc
I have two tables fooditem(itemid,itemname,itemprice)
and another rating(itemid,vote,itemid,username)
我有两个表
fooditem(itemid,itemname,itemprice)
和另一个rating(itemid,vote,itemid,username)
How to get sum of votes groupby itemid in rating table and the itemname ,itemprice corresponding to the total rating on each food item. 如何获得评分表中groupid项的投票总和以及对应于每个食品项的总评分的项名,itemprice。 sql query is
sql查询是
select table2.sum(votes),table1.itemname,table1.itemprice from table1,table2 where table1.itemid==table2.itemid group by table2.itemid
I started with this query.Bad luck! 我从这个查询开始。运气不好!
List<FoodView> items= (from a in db.FoodItems
join b in db.Ratings on a.itemid equals b.itemid
group b by b.itemid into g
select new FoodView
{
itemname=g.Select(d=>d.itemname),
itemprice=g.Select(d=>d.itemprice),
vote=g.Sum(d=>d.vote)
}).ToList();
FoodViewModel vm = new FoodViewModel { Foodviews= items}; FoodViewModel vm =新的FoodViewModel {Foodviews = items};
My Model is 我的模特是
public class FoodViewModel
{
public List<FoodView> Foodviews { get; set; }
public FoodViewModel()
{
Foodviews = new List<FoodView>();
}
}
public class FoodView
{
public long? itemid { get; set; }
public string itemname { get; set; }
public long? itemprice { get; set; }
public long? vote { get; set; }
}
Please use following query:
var foodViewsList = (from t in fooditems
join r in ratings on t.itemid equals r.itemid
group r by new { r.itemid, t.itemname, t.itemprice } into g
select new FoodView
{
itemid = g.Key.itemid,
itemname = g.Key.itemname,
itemprice = g.Key.itemprice,
vote = g.Sum(x => x.vote)
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.