获得前5个产品使用实体框架每个类别和子类别 [英] Get Top 5 Products in Each Category and Subcategory using Entity Framework

查看:244
本文介绍了获得前5个产品使用实体框架每个类别和子类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的ASP.NET 4.5 Web项目使用实体框架。我的产品的表,每个产品与它的类别和子类别。一个类别可能没有一个子类。

I am using Entity Framework in my ASP.NET 4.5 web project. I have a table of products, each product with its category and sub-category. A category might not have a sub-category.

表产品


  • 标识

  • 名称

  • CATEGORY_ID

  • subcategory_id

  • 日期

表分类


  • CATEGORY_ID

  • parent_category_id

如果类有一个 parent_category_id = 0 ,这是一个父类,否则它的另一个类别上相同的表子类别。

if the category has a parent_category_id = 0, it's a parent category, else it's a sub category of another category on that same table.

我想创建实体框架查询按日期从最新的一个最古老的一个检索前5个产品的每个子类别。

I want to create a query in Entity Framework to retrieve the top 5 products for each subcategory by date from the newest one to the oldest one.

最后,我要建表,显示前5的最新产品为每个子类别。

At the end, I want to build tables that show the top 5 latest products for each subcategory.

一个产品可以belogn只有一个子类别。

A product can belogn to only one subcategory.

有对这种类型的问题与一种类别的答案,但没有子类别。我的问题是特定于特定的数据库结构。谢谢你。

There are answers for this type of question with one category, but without sub-categories. My question is specific for that specific database structure. Thanks.

推荐答案

这里是code,使用 lembda前pressions前5个产品

here is the code for Top 5 products using lembda expressions

YourEntities DBContext = new YourEntities();

List<Category> categories = DBContext.categories.Where(d=> d.category_id!=null).ToList();
List<Product> prodcuts = null;
foreach (var item in categories)
{
    prodcuts = DBContext.Products.Where(d => d.category_id== item.category_id)
                 .OrderByDescending(d => d.date)
                                 .Take(5)
                                 .ToList();
}

这篇关于获得前5个产品使用实体框架每个类别和子类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆