0

我想编写一个 Linq 查询,它将返回该公司所有产品的列CompanyNameSupplier数量。你能帮助我吗?

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

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。

4

2 回答 2

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()
              };
于 2013-06-29T08:50:43.483 回答
2

使用 group join (即join...into)将供应商与产品加入并获得供应商的所有产品在组中:

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()
}
于 2013-06-29T09:08:23.383 回答