简体   繁体   English

在ViewModel ASP.NET MVC和C#中对数据进行分组

[英]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. 我在理解如何在ViewModel中对数据进行分组,填充数据并将其传递给视图时遇到了麻烦。 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. 我的目标很简单,但是作为ASP.NET MVC中的新手,我很难实现它。 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. 假设使用groupBy查询为每个产品实例有1条记录,则可以获取数量。

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()
                    });

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

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