2014-02-12 55 views
0

我有兩個表fooditem(itemid,itemname,itemprice)和另一rating(itemid,vote,itemid,username)LINQ查詢採取總量和正常列在C#中的MVC

票如何獲得和GROUPBY的itemid排名表和ITEMNAME,相當於總得分上每種食品ITEMPRICE項目。 sql查詢是

select table2.sum(votes),table1.itemname,table1.itemprice from table1,table2 where table1.itemid==table2.itemid group by table2.itemid 

我開始用這個查詢。很幸運!

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};

我的模型是

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; } 

} 
+0

任何一個可以幫助?這個LINQ查詢http://stackoverflow.com/questions/13471974/selection-with-join-and-sum - 從表式-SQL服務器 – user3300195

回答

0
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();