又一个“查询主体必须以select子句或组子句结束”

时间:2017-10-28 14:14:21

标签: c# linq linq-to-sql

此查询确实有效,但我尝试将这两个步骤合并为一个查询。

var query1 = from b in db.GetTable<Boats>()
             from o in db.GetTable<Offices>()
             from u in db.GetTable<Users>()
             .Where
             (u =>
              u.UserId == b.Handling_broker &&
              o.Office == b.Handling_office &&
              b.Status == 2 &&
              officesToInclude.Contains(b.Handling_office)
             )
             select new
             {
                hOffice = o.Name,
                bName = u.Name
             };

var query2 = query1.GroupBy(t => new { office = t.hOffice, name = t.bName })
          .Select(g => new { Office = g.Key.office, Name = g.Key.name, Count = g.Count() });

如果我尝试使用以下查询组合这两个查询,它会给我“查询正文必须以select子句或group子句结束”错误。

var query1 = from b in db.GetTable<Boats>()
             from o in db.GetTable<Offices>()
             from u in db.GetTable<Users>()
             .Where
             (u =>
              u.UserId == b.Handling_broker &&
              o.Office == b.Handling_office &&
              b.Status == 2 &&
              officesToInclude.Contains(b.Handling_office)
             )
            .GroupBy(t => new { office = t.Office, name = t.Name })
            .Select(g => new { Office = g.Key.office, Name = g.Key.name, Count = g.Count() });

我想我必须添加一些选择,但我无法弄清楚是什么。 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您的查询必须包含select子句。 .Where(...).GroupBy(...).Select(...)仅在db.GetTable<Users>()上。类似的东西:

var query1 = from b in db.GetTable<Boats>()
             from o in db.GetTable<Offices>()
             from u in db.GetTable<Users>().Where(u => u.UserId == b.Handling_broker &&
                                                       o.Office == b.Handling_office &&
                                                       b.Status == 2 &&
                                                       officesToInclude.Contains(b.Handling_office))
                         .GroupBy(t => new { office = t.Office, name = t.Name })
                         .Select(g => new { Office = g.Key.office, Name = g.Key.name, Count = g.Count() })
             select new { /* Desired properties */};

但我认为你正在寻找类似的东西:

var result = from b in db.GetTable<Boats>()
             from o in db.GetTable<Offices>()
             from u in db.GetTable<Users>()
             where u.UserId == b.Handling_broker &&
                 o.Office == b.Handling_office &&
                 b.Status == 2 &&
                 officesToInclude.Contains(b.Handling_office))
             group 1 by new { t.Office, t.Name } into g
             select new { Office = g.Key.Office, Name = g.Key.Name, Count = g.Count() };