2011-06-06 47 views
1

我很困扰我遇到的一个问题。 其中,我有这个表在我的数据库:在实体框架中获取表格的前N行

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

我想十大热销产品中使用MVC2实体框架。我怎样才能做到这一点?

////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////// 继kip和Pr0fess0rX的建议之后,这就是我迄今为止所做的,它似乎工作:

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())); 
} 

这是正确的方法?

+0

继thekip的和Pr0fess0rX的意见,这是我迄今所做的,它似乎是工作: '使用(实体分贝=新实体()){ \t VAR groupedProducts =(从对在db.Products \t \t \t \t \t \t加入S IN db.SoldToData \t \t \t \t \t \t \t上p.productId等于s.productId \t \t \t \t \t \t群p由p.id \t \t \t \t \t \t \t成ProductGroup \t \t \t \t \t \t \t的OrderBy ProductGroup.Count( )降序 \t \t \t \t \t \t \t选择ProductGroup)。取(10).ToList(); \t List products = new List (); \t products.AddRange(groupedProducts.Select(gp => gp.First())); }' 这是正确的方法吗? – Slavisa 2011-06-06 12:11:08

回答

4

如果你有一个IQueryable查询,你可以使用排序依据等进行订购,然后采取(10)的数据源?

+0

嗨thekip。感谢您的快速回复。我还没有使用IQueryable。我刚刚看了一下。你能举个例子吗? – Slavisa 2011-06-06 11:12:11

+0

如何从数据库中获取单个行?例如,您如何通过ID获得产品? 当使用实体框架(或任何其他ORM)时,我肯定会使用IQueryable来访问我的数据库。 – thekip 2011-06-06 11:20:53

+0

'使用(Entities db = new Entities()) var product =(from p in db.Product where p.productId == id select a).Single(); }' – Slavisa 2011-06-06 11:29:59

1
  1. 加入产品和客户
  2. 集团他们,让每个客户的产品
  3. 为了通过计数递减计数。
  4. 以时代的前10
  5. 得到的结果产品名称(前10名)