Reputation: 561
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.
Upvotes: 0
Views: 1278
Reputation: 4341
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()
});
Upvotes: 3