简体   繁体   中英

Grouping data in ViewModel ASP.NET MVC & C#

I'm having trouble understanding how to group data in ViewModel, fill it and pass it to the view. I use Entity Framework with a code-first approach.

My domain model is:

public class Product
{
        public int ProductId { get; set; }

        [DisplayName("Name of the product")]
        public string ProductName { get; set; }

        [DisplayName("Descritpion of the product")]
        public string ProductDescription { get; set; }

        [DisplayName("Price of the product")]
        public decimal ProductPrice { get; set; }

        public int EAN { get; set; }

        public int CategoryId { get; set; }

        public virtual Category Categories { get; set; }
}

I also have my view model:

public class ProductIndexGroup
{
    public int EAN { get; set; }
    public string ProductName { get; set; }
    public int Quantity { get; set; }
}

What I am aiming for is fairly simple, but as a newbie in ASP.NET MVC, I'm having trouble achieving it. I would like to group data using my view model and display it in view like this:

EAN      Product Name     Quantity
-----------------------------------
12354    Product1         5
98765    Product2         2

Any help is greatly appreciated.

You can get the quantities, assuming that you have 1 record for each instance of a product using a groupBy query.

Something to note is that this is not the most ideal data structure as you will have repeated records for all of your quantities. It will become very inefficient to store thousands of duplicate records to keep track of quantity.

var products = productCollection //This is however you are accessing your product db set 
                   .GroupBy(c => new { c.EAN, c.ProductName})
                   .Select(c => new ProductViewModel { 
                       EAN = c.Key.EAN, 
                       ProductName = c.Key.ProductName, 
                       Quantity = c.Count()
                    });

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