如何使用LINQ从具有Count和Group By?的多个表中选择列?
这是我在C#中的SQL查询,我想将其转换为LINQ查询。
string sqlProduct = string.Format(@"SELECT protype.idType, TypeName, **COUNT(idPro) as proNumber**
FROM protype, product
WHERE protype.idType=product.idType
**GROUP BY protype.idType, TypeName**
ORDER BY TypeName");
DataTable dt = new DataTable();
dt = Shop_Query.Select_Query(sqlProduct);
lvMenu.DataSource = dt;
lvMenu.DataBind();
答案 0 :(得分:0)
试试这个:
var query = dbContext.Protypes.Join(dbContext.Products,
protype => protype.idType,
product => product.idType,
(protype, product) => new { Protype = protype, Product = product })
.GroupBy(s => new { s.Protype.idType, Product.TypeName })
.Select(s => new
{
IdType = s.First().Protype.idType,
TypeName = s.First().Product.TypeName,
Count = s.Count()
});
此查询中有很多假设。
dbContext
Products
和ProTypes
TypeName
字段属于Product table