首页 > 解决方案 > 在 ViewModel ASP.NET MVC 和 C# 中对数据进行分组

问题描述

我无法理解如何在 ViewModel 中对数据进行分组、填充并将其传递给视图。我将实体框架与代码优先方法一起使用。

我的域模型是:

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

我也有我的视图模型:

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

我的目标相当简单,但作为 ASP.NET MVC 的新手,我很难实现它。我想使用我的视图模型对数据进行分组并将其显示在视图中,如下所示:

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

任何帮助是极大的赞赏。

标签: c#asp.net-mvcentity-framework

解决方案


假设您使用 groupBy 查询对产品的每个实例都有 1 条记录,您可以获得数量。

需要注意的是,这不是最理想的数据结构,因为您将重复记录所有数量。存储数千条重复记录以跟踪数量将变得非常低效。

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

推荐阅读