将ms sql“group by”转换为linq转换为sql

时间:2009-02-16 19:47:09

标签: sql sql-server linq

我有两张桌子,产品和类别。我如何将以下sql查询转换为linq格式?

select c.Name, c.DisplayName, count(p.id) from categories as c
LEFT join products as p on p.categoryId = c.id
group by c.Name, c.DisplayName

某些类别中将包含0个产品,因此LEFT JOIN非常重要

3 个答案:

答案 0 :(得分:2)

如果您在模型中正确定义了关系,那么customers表应与所有产品关联,这样您就可以使用'c.Products'访问与客户关联的产品。然后应该能够写出这样的东西:

  var q = 
    from c in categories
    select new { c.Name, c.DisplayName, Count = c.Products.Count() }

吨。

答案 1 :(得分:0)

dc.categories
.Select(c => new
{
  Name = c.Name,
  DisplayName = c.DisplayName,
  TheCount = c.Products.Count()
}

如果您想在其他情况下进行左连接,请查看“群组加入”。

dc.categories
.GroupJoin(dc.products,
  c => c.id,
  p => p.categoryid,
  (c, g) => new { Name = c.Name, TheCount = g.Count() }
);

答案 2 :(得分:0)

显示分组。

 var q =   from c in db.categories
    group c by new {c.Name , c.DisplayName} into alias
    select new { alias.Name, 
                 alias.DisplayName, 
                 Count = alias.Count(p => p.id) 
                }