-1

I have the query 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

This code needs to be written in Entity Framework. How to write?

1

2 Answers 2

1

Try this

var result = dbContext.Products
                      .GroupBy(p => p.Name)
                      .Select(g => new { Name = g.Key, Number = g.Count()}
                      .OrderByDescending(x => x.Number)
                      .Take(10)

If you are counting the number of Orders per product, then try this

var result = dbContext.Orders
                      .GroupBy(o => o.Product.Name)
                      .Select(g => new { Name = g.Key, Number = g.Count()}
                      .OrderByDescending(x => x.Number)
                      .Take(10)
0

Ok - I've not tested this, but it should do what you need

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);
  • you have here the join between orders and products as the inner most query (q1).
  • We only care about selecting the name (duplicated for each order) hence the line select p.NAME
  • This is grouped with the group by statement - and we get select the Key (the thing that is being grouped by - in this case NAME) and the Count of items in that group. This becomes the subquery q2.
  • finally we order q2 by the number descending, and use .Take(10) to get the top 10.

Not the answer you're looking for? Browse other questions tagged or ask your own question.