1

I'm trying to write this select in LINQ but Im not successful to fix it for long time. I also tried LINQ - join with Group By and get average but it doesn't work in my code. It is obviously that I'm wrong.

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

1 回答 1

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) 
                               }); 
于 2013-05-03T02:06:52.987 回答