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

C# Entity Framework如何将同一卡车的多关联行合并存储到单个对象

解决方案

你可以通过按卡车唯一标识分组、拼接特性字段的方式解决重复行问题,修改后的代码如下:

public static List<TruckWithModel> GetAllTrucks()
{
    using (DAD_BaldipContext ctx = new DAD_BaldipContext())
    {
        // 先加载所有关联数据到内存,避免EF服务器端求值不支持字符串拼接的问题
        var associationList = ctx.TruckFeatureAssociation
                   .Include(t => t.Truck)
                   .Include(tf => tf.Feature)
                   .Include(tm => tm.Truck.TruckModel)
                   .ToList();

        // 按卡车注册号(唯一标识)分组,合并同一卡车的所有特性
        return associationList
                   .GroupBy(it => it.Truck.RegistrationNumber)
                   .Select(group => new TruckWithModel
                   {
                       Colour = group.First().Truck.Colour,
                       Size = group.First().Truck.TruckModel.Size,
                       RentalPrice = group.First().Truck.DailyRentalPrice,
                       Status = group.First().Truck.Status,
                       Model = group.First().Truck.TruckModel.Model,
                       Rego = group.Key,
                       Features = string.Join("、", group.Select(item => item.Feature.Description))
                   })
                   .ToList();
    }
}

逻辑说明

原来的查询以TruckFeatureAssociation中间表的每条记录为单位生成输出对象,所以卡车有N个关联特性就会生成N条重复记录。调整后:

  1. 先把所有需要的关联数据加载到内存
  2. 按卡车的唯一标识(注册号RegistrationNumber)分组,同一卡车的所有关联记录会被归到同一个分组
  3. 每个分组仅生成一个TruckWithModel对象,基础属性取分组内第一条记录的卡车属性,Features字段通过string.Join拼接该分组下所有特性的描述

如果你的EF Core版本在3.0及以上,也可以直接从Truck表出发查询,写法更简洁:

public static List<TruckWithModel> GetAllTrucks()
{
    using (DAD_BaldipContext ctx = new DAD_BaldipContext())
    {
        return ctx.Trucks // 此处需替换为你项目中IndividualTruck对应的DbSet名称
                   .Include(t => t.TruckModel)
                   .Include(t => t.TruckFeatureAssociations) // 此处需替换为卡车到中间表的导航属性名
                   .ThenInclude(ta => ta.Feature)
                   .Select(t => new TruckWithModel
                   {
                       Colour = t.Colour,
                       Size = t.TruckModel.Size,
                       RentalPrice = t.DailyRentalPrice,
                       Status = t.Status,
                       Model = t.TruckModel.Model,
                       Rego = t.RegistrationNumber,
                       Features = string.Join("、", t.TruckFeatureAssociations.Select(ta => ta.Feature.Description))
                   })
                   .ToList();
    }
}

内容的提问来源于stack exchange,提问作者BoogieMan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:15:08