简体   繁体   中英

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!

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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