如何选择CompanyName及其产品数量?

时间:2013-06-29 08:37:24

标签: c# linq entity-framework

我想写一个将返回的Linq查询,CompanyName Supplier列{以及此公司所有产品的数量。你能帮助我吗?

到目前为止,我得到了这个:

var company = from pro in db.Products
              join sup in db.Suppliers
                  on pro.SupplierID equals sup.SupplierID
              group pro by pro.SupplierID 
              into g
              select new { Name = g.Key, COUNT = g.Count() };

但这会返回SupplierID而不是CompanyName。数据库是Northwnd。

2 个答案:

答案 0 :(得分:2)

以下编译并运行Linq-for-objects。我不能保证Linq-to-SQL是否会应付。

var company = from sup in db.Suppliers
              select new
              {
                  Name = sup.CompanyName,
                  COUNT = db.Products
                      .Where(pro => pro.SupplierID == sup.SupplierID)
                      .Count()
              };

答案 1 :(得分:2)

使用群组加入(即加入...进入)将供应商与产品合并,并将所有供应商的产品分组:

from s in db.Suppliers
join p in db.Products
   on s.SupplierID equals p.SupplierID into g
select new {
   s.CompanyName,
   ProductsCount = g.Count()
}