【发布时间】:2021-09-02 12:37:22
【问题描述】:
我有一个包含不同值的 SQL 数据库:名称、尺寸、重量、价格和材料。
每个产品可以有多种材料。 如下例:产品 1 有 3 种材料,产品 2 有 2 种材料。
| Name | Dimension | Weight | Price | Material |
|---|---|---|---|---|
| Product 1 | 340 | 3.0 | 23.55 | Steel |
| Product 1 | 340 | 3.0 | 23.55 | Brass |
| Product 1 | 340 | 3.0 | 23.55 | Copper |
| Product 2 | 214 | 2.3 | 13.25 | Steel |
| Product 2 | 214 | 2.3 | 13.25 | Gold |
我现在想要实现的事情,是按名称对这些数据进行分组,并将所有材料组合成一个材料数组。
注意:为每种材料添加了一条新的 sql 记录,但名称、尺寸、重量和价格在这些行中保持不变。 (只有材料变化)
Public Class Product
Public Property name As String
Public Property dimension As Integer
Public Property weight As Double
Public Property price As Double
Public Property materials() As String
End Class
到目前为止我所尝试的:
Using conn As SqlConnection = New SqlConnection("Data source
=db;Initial Catalog=ProductData;Integrated
security=True")
Dim cmd As New SqlCommand("select * from dbo.Product_data_db",
conn)
Dim adapter As New SqlDataAdapter(cmd)
adapter.Fill(table)
End Using
Dim products As List(Of Product) = table.AsEnumerable().
Select(Function(x) New Product(x)).
GroupBy(Function(x) x.name).
Select(Function(y) New Product With
{.name = y.Key, .materials = y.Select(Function(x) x.materials()}).ToList
预期结果:
包含 2 个项目的列表(产品):
第 1 项:
- name = "产品 1"
- 尺寸 = 340
- 重量 = 3.0
- 价格 = 23.55
- 包含材料的字符串数组 = 钢、黄铜、铜
第 2 项:
- name = "产品 2"
- 尺寸 = 214
- 重量 = 2.3
- 价格 = 13.25
- 包含材料的字符串数组 = 钢、金
【问题讨论】:
-
什么是
table?一个类型化的 DataTable 还是这真的是 Linq-To-Sql/Linq-To-Entities?顺便说一句,为什么您没有该产品的外键?我猜这个表是ProductMaterial,它链接到Product,至少应该是这样。 -
@TimSchmelter 嗨,蒂姆,我在帖子中添加了代码。我使用 SqlDataAdapter 填充表,我不知道这是否是最好的方法。如果您知道更好的方法,请告诉我!
-
按照 Tim 的建议标准化您的数据(并使用 EF;它会为您执行此操作)
-
@CaiusJard 你好 CaiusJard,你能告诉我 EF 代表什么吗?我从来没有听说过:)
-
实体框架
标签: sql vb.net list linq class