如何将where子句添加到具有分组

时间:2017-06-05 03:57:47

标签: entity-framework linq

我试图找到每个用户的预订数量。这段代码效果很好 - 它可以连接到预订并对它们进行分组,然后进行计数。

var bookingsByUser = from u in _repo.Users()
  join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
  into g
  select new { UserId = u.UserId, TotalBookings = g.Count() };

但是,我现在想要排除某个餐馆,所以我尝试添加一个where子句:

var bookingsByUser = from u in _repo.Users()
  join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
  where b.RestaurantId != 21 
  into g
  select new { UserId = u.UserId, TotalBookings = g.Count() };

但是现在我收到错误"查询正文必须以select子句或group子句结束"。我似乎无法使用"其中"在连接表上,在分组之前过滤记录。有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

var bookingsByUser = from u in _repo.Users()
                     join b in _repo.Bookings() on u.UserId equals b.CreatedByUserId
                     where b.RestaurantId != 21
                     group b by u.UserId into sub
                     select new {
                         UserId = sub.Key,
                         TotalBookings = sub.Count()
                     };