2013-05-03 81 views
1

我試圖在LINQ中編寫此選擇,但我沒有成功修復它很長時間。我也試過LINQ - join with Group By and get average,但它在我的代碼中不起作用。很顯然,我錯了。LINQ - 多組加入並獲得平均值

SQL:

SELECT name_type, AVG(t.price) as avgPrice FROM type tp 
JOIN location l ON l.ID_type = tp.ID 
JOIN event e ON e.ID_location = l.ID 
JOIN ticket t ON t.ID_event = e.ID 
GROUP BY tp.name_type 

LINQ:

var q3 = from l in db.location 
join tp in db.type on l.ID_type equals tp.ID 
join e in db.event on l.ID equals u.ID_location 
join t in db.ticket on e.ID equals t.ID_event 
group tp by new {Type_name = tp.type_name} into grp 
select new 
{ 
    Type_name = grp.Key.type_name, 
    avgPrice = grp.Average(x => x.ticket.price) 
}; 

回答

3

有幾個問題:

  1. 沒有在第二個連接—我相信u.ID_location需求是e.ID_location錯誤。
  2. 我認爲你是在錯誤的實體上進行分組,嘗試按t分組而不是tp
  3. 您不需要group by中的匿名類型。

試試這個:

var results = 
    from l in db.location 
    join tp in db.type on l.ID_type equals tp.ID 
    join e in db.event on l.ID equals e.ID_location 
    join t in db.ticket on e.ID equals t.ID_event 
    group t by new tp.type_name into grp 
    select new 
    { 
      Type_name = grp.Key, 
      avgPrice = grp.Average(x => x.price) 
    }; 

如果你碰巧有你的實體之間建立導航屬性,這將是一個容易得多。這是相當困難告訴實體如何應該有關係,但我想這樣的事情會的工作:

// average ticket price per location type 
var results = 
    from t in db.ticket 
    group t by t.event.location.type.type_name into g 
    select new 
    { 
     Type_name = g.Key, 
     avgPrice = g.Average(x => x.price) 
    }; 

或者用流利的語法:

var results = db.ticket.GroupBy(t => t.event.location.type.type_name) 
         .Select(g => new 
           { 
            Type_name = g.Key, 
            avgPrice = g.Average(x => x.price) 
           }); 
+0

謝謝你洙多!它完美的作品:)現在我可以去嘗試更難的選擇... – Matwosk 2013-05-03 11:51:08