简体   繁体   English

保持一个类别中的项目数

[英]Keeping count of items in a category

New to MVC so apologies if a quick google would have answered this, links to articles explaining this or examples where this is used would be appreciated! MVC的新用户如果快速google会回答这个问题,那么道歉,链接到解释此内容的文章或使用此示例的示例将不胜感激!

Basically, I have a list of products in categories/sub categories, and want to be able to output the a list of them with the number of products in each sub category such as: 基本上,我有一个类别/子类别的产品列表,并希望能够输出每个子类别中的产品数量的列表,例如:

Computers
 - Laptops  (4)
 - Tablets  (9)
 - Netbooks (3)

I am using EF Code First, and I'm not sure how best to organise this. 我正在使用EF Code First,我不确定如何最好地组织它。 I could iterate through my list of products and get a count for each one, but this seems inefficient. 我可以遍历我的产品列表并获得每个产品的计数,但这似乎效率低下。 I could also store a count variable in the model for each subcategory, and increment it each time a new product is added. 我还可以在每个子类别的模型中存储一个计数变量,并在每次添加新产品时递增它。

Basically, I'm after a 'best-practice' approach to knowing how to do this, so I can learn to do it right from the start. 基本上,我正在采用'最佳实践'的方法来了解如何做到这一点,所以我可以从一开始就学会这样做。

You could have the database perform the querying: 您可以让数据库执行查询:

var model = db
    .Categories
    .Select(c => new MyViewModel
    {
        Name = c.Name,
        ProductsCount = c.Products.Count()
    })
    .ToList();

Then inside your view you will have the name and total products count in the view model so that when you are displaying the list you will be able to show this information. 然后在视图中,您将在视图模型中获得名称和总产品数,这样当您显示列表时,您将能够显示此信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM