c# - 在 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
任何帮助是极大的赞赏。
解决方案
假设您使用 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()
});
推荐阅读
- c++ - OpenGL着色器存储缓冲区/memoryBarrierBuffer
- c# - 如何将组合框绑定到 ObservableCollection 列表中的某个项目 - WPF?
- c++ - 从多个模板化基类派生时出现“隐藏重载的虚函数”警告
- reactjs - 为什么我应该使用 Ant Design 而不是其他前端库
- ios - 将设备升级到 iOS12 后应用程序崩溃
- java - Gradle 在使用 annotationProcessor 时引发错误:以下任务之间的循环依赖关系
- javascript - 材质 ui 日期选择器显示选定值 -1
- sum - 使用 GAMS 中的 sum 函数对变量子集求和
- javascript - 仅使用一次替换
- java - 在 Java 中将 blob 附加/嵌入到 PDF