如何在LINQ多表关联查询中获取包含版本列表的品牌产品数据
如何查询品牌名称、产品名称及对应版本列表
现有表结构与数据
Brand表
| Id | Name | IsRegistered |
|---|---|---|
| 1 | ABC | True |
| 2 | XYZ | True |
Product表
| Id | Name | BrandId | Active | Version |
|---|---|---|---|---|
| 1 | Soap | ABC | True | 1.0 |
| 2 | Soap | ABC | True | 2.0 |
| 3 | Oil | Xyz | True |
需求
输出品牌名称(BrandName)、产品名称(ProductName),以及对应产品的所有版本组成的列表。
原查询的问题
你的原查询存在几个问题:
- 语法错误:引用变量错误(比如
Brand.Id应该是b.Id,P.Active应该是p.Active,IsRegisterd = true应该是b.IsRegistered == true) - 逻辑错误:用左连接后逐行展开结果,无法将同一产品的多个版本聚合为列表
- 连接条件错误:Brand表的Id是数字,但Product表的BrandId是品牌名称字符串,应该用
b.Name和p.BrandId关联
正确实现方式
通过分组查询,将同一品牌下的同一产品的版本聚合为列表,代码如下:
from b in DbContext.Brand // 筛选已注册的品牌 where b.IsRegistered == true // 关联对应品牌下的活跃产品 join p in oneAssetContext.Products on b.Name equals p.BrandId into productGroup from product in productGroup.Where(p => p.Active == true).DefaultIfEmpty() // 按品牌名称和产品名称分组,聚合版本 group product by new { BrandName = b.Name, ProductName = product.Name } into grouped select new SinglePoductDetails { BrandName = grouped.Key.BrandName, ProductName = grouped.Key.ProductName, // 收集所有非空版本,空版本会被过滤,也可替换为默认值如"" Versions = grouped.Select(p => p.Version).Where(v => v != null).ToList() }
说明
- 若需保留空版本(比如Product表中Version为空的记录),可去掉
.Where(v => v != null),改为p.Version ?? string.Empty将null转为空字符串 - 如果
SinglePoductDetails类中版本列表的属性名不是Versions,请替换为对应的名称(比如原代码中的Version,但该属性需定义为集合类型)
内容的提问来源于stack exchange,提问作者Pinky
相关产品推荐
相关产品推荐

