查询实体选择,内连接和计数

时间:2015-02-02 15:56:35

标签: c# sql linq entity-framework

我想翻译这个SQL查询:

SELECT FirstName,LastName, WaiterId, Count(*) AS compte 
FROM Waiter
INNER JOIN Client on Waiter.Id = Client.WaiterId
GROUP BY WaiterId,lastname, firstname 
ORDER BY compte DESC;

在实体框架中。

我试过这样的事情:

           var query = (from w in db.Waiter
                     join c in db.Client on w.Id equals c.WaiterId
                     group c by c.WaiterId into g
                     //orderby 
                     select new
                     {
                         WaiterId = g.Key,
                         count = g.Count()
                     });

但我的选择不起作用。我无法选择FirstName和LastName,我甚至不知道我的计数是否良好。

1 个答案:

答案 0 :(得分:2)

您需要在组中包含所有属性。

var query = (from w in db.Waiter
             join c in db.Client on w.Id equals c.WaiterId
             group c by new { c.FirstName, c.LastName, c.WaiterId} into g
             orderby g.Count() descending
             select new
             {
                  FirstName = g.Key.FirstName,
                  LastName  = g.Key.LastName,
                  WaiterId  = g.Key.WaiterId,
                  count     = g.Count()
              });