开发者

Fetch top N rows of the table in Entity Framework

开发者 https://www.devze.com 2023-03-10 11:53 出处:网络
I\'m kind of stuck with a problem that I\'m having. Among开发者_开发问答 others, I have this tables in my DB:

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?


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


  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)
0

精彩评论

暂无评论...
验证码 换一张
取 消