我有查询sql:
select top 10 NAME, count(*) as Number
from Products as pro
join Orders as ord on ord.ID_PRODUCT = pro.ID
group by NAME
order by Number desc
此代码需要在Entity Framework中编写。 怎么写?
答案 0 :(得分:1)
试试这个
var result = dbContext.Products
.GroupBy(p => p.Name)
.Select(g => new { Name = g.Key, Number = g.Count()}
.OrderByDescending(x => x.Number)
.Take(10)
如果您计算每件产品的订单数量,请尝试此
var result = dbContext.Orders
.GroupBy(o => o.Product.Name)
.Select(g => new { Name = g.Key, Number = g.Count()}
.OrderByDescending(x => x.Number)
.Take(10)
答案 1 :(得分:0)
好的 - 我没有测试过这个,但它应该做你需要的
var result =
(
from q2 in
(
from q1 in
(
from p in Products
join o in orders on p.ID equals o.ID_PRODUCT
select p.NAME
)
group q1 by q1 into grp
select new{NAME = grp.Key, Number = grp.Count()}
)
orderby q2.Number descending
select q2
).Take(10);
select p.NAME