我正在尝试在LINQ中编写此选择但是我很长时间没有成功修复它。我也试过LINQ - join with Group By and get average,但它在我的代码中不起作用。显然我错了。
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)
};
答案 0 :(得分:3)
有一些问题:
u.ID_location
需要e.ID_location
。 t
而不是tp
进行分组。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)
});