You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LINQ多表关联查询中获取包含版本列表的品牌产品数据

如何查询品牌名称、产品名称及对应版本列表

现有表结构与数据

Brand表

IdNameIsRegistered
1ABCTrue
2XYZTrue

Product表

IdNameBrandIdActiveVersion
1SoapABCTrue1.0
2SoapABCTrue2.0
3OilXyzTrue

需求

输出品牌名称(BrandName)、产品名称(ProductName),以及对应产品的所有版本组成的列表。

原查询的问题

你的原查询存在几个问题:

  1. 语法错误:引用变量错误(比如Brand.Id应该是b.Id,P.Active应该是p.Active,IsRegisterd = true应该是b.IsRegistered == true)
  2. 逻辑错误:用左连接后逐行展开结果,无法将同一产品的多个版本聚合为列表
  3. 连接条件错误: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 14:52:25