In Entity Framework, get the top N rows in the table.

asp.net-mvc-2 c# entity-framework

Question

I'm kind of stuck with a problem that I'm having. Among others, I have this tables in my DB:

Product (int productId, ...otherProductInfo)
Customer (int customerId, ...otherCustomerInfo)
SoldToData ( int productId, int customerId)

I want to get top ten selling products using Entity Framework in MVC2. How can I do that?

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Following thekip's and Pr0fess0rX's advices, this is what I have done so far, and it seems to be working:

using (Entities db = new Entities())
{
    var groupedProducts = (from p in db.Products
                        join s in db.SoldToData
                            on p.productId equals s.productId
                        group p by p.id
                            into ProductGroup
                            orderby ProductGroup.Count() descending
                            select ProductGroup).Take(10).ToList();
     List<Products> products = new List<Products>();
     products.AddRange(groupedProducts.Select(gp => gp.First()));
}

Is this the proper way?

1
1
6/6/2011 12:16:45 PM

Accepted Answer

If you have an IQueryable to query the datasource you could use orderby etc for ordering followed by Take(10)?

4
6/6/2011 11:00:30 AM

Popular Answer

  1. Join both products and customer
  2. Group them and get the count of products per customer
  3. Order descending by the count.
  4. Take top 10 of the times
  5. Get the name of the result products (top 10)


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow