You need to enable JavaScript to run this app. 如何使用AutoMapper将父子实体关系转换为合并双方属性的ItemDto列表
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AutoMapper将父子实体关系转换为合并双方属性的ItemDto列表

AutoMapper 实现父子实体扁平化Dto列表的配置方案

核心问题说明

仅靠现有的两个单对象映射配置,无法达到预期效果。AutoMapper默认的集合映射逻辑只会做同层级元素的一一对应,遇到带Versions导航属性的父实体时,因为ItemDto没有和Versions集合对应的目标属性,所有子版本的Name、Date信息会被直接丢弃,最终生成的Dto数量和父实体数量完全一致,无法实现拆分多条记录的效果。
要实现和手动编码一致的SelectMany扁平化逻辑,需要在现有Profile基础上补充自定义转换规则。

正确的Profile配置实现

已有的两个单对象映射(ItemEntity->ItemDto、ItemVersionEntity->ItemDto)可以全部保留,后续也可以复用这两个规则做属性填充,只需要补充扁平化的转换配置,有两种常用实现方式:

写法1:直接定义集合级别的映射规则

直接在Profile中添加从父实体集合到目标Dto列表的转换逻辑:

public class RepositoryMappingProfile : Profile
{
    public RepositoryMappingProfile()
    {
        // 保留原有单实体映射,用于后续属性填充
        CreateMap<ItemEntity, ItemDto>();
        CreateMap<ItemVersionEntity, ItemDto>();

        // 核心扁平化配置
        CreateMap<IEnumerable<ItemEntity>, List<ItemDto>>()
            .ConvertUsing((itemEntities, dtoList, context) =>
            {
                return itemEntities.SelectMany(parent => 
                    parent.Versions.Select(child => 
                    {
                        // 先填充父实体属性,再填充子版本属性,无属性重叠不会互相覆盖
                        var dto = context.Mapper.Map<ItemDto>(parent);
                        context.Mapper.Map(child, dto);
                        return dto;
                    })
                ).ToList();
            });
    }
}

写法2:定义单父实体到多Dto的映射规则

AutoMapper支持自动对集合映射做展开——当源集合的单个元素被配置为映射到目标的一个集合时,AutoMapper会自动对所有元素生成的子集合做SelectMany扁平化,最终拼成连续的目标Dto列表。这种写法不需要单独写集合级别的配置:

public class RepositoryMappingProfile : Profile
{
    public RepositoryMappingProfile()
    {
        CreateMap<ItemEntity, ItemDto>();
        CreateMap<ItemVersionEntity, ItemDto>();

        // 配置单个父实体对应的多个Dto生成规则
        CreateMap<ItemEntity, IEnumerable<ItemDto>>()
            .ConvertUsing((parent, _, context) =>
            {
                return parent.Versions.Select(child => 
                {
                    var dto = context.Mapper.Map<ItemDto>(parent);
                    context.Mapper.Map(child, dto);
                    return dto;
                }).ToList();
            });
    }
}

配置优势说明

  • 完全复用已有的单对象映射规则,不需要硬编码给Dto属性赋值。后续实体或Dto新增字段时,只要在原有单对象映射中补充配置,扁平化逻辑不需要修改
  • 最终输出效果和手动foreach循环的结果完全一致:单个父实体带N个子版本,就生成N条Dto,每条同时携带对应父属性和子属性

效果验证

使用和手动实现完全一致的测试数据调用映射:

List<ItemEntity> all = /* 准备测试用的父实体集合 */;
List<ItemDto> result = mapper.Map<List<ItemDto>>(all);

最终输出结果和手动实现完全相同:

IdkeyNameDate
1aname110/09/2020 09:37:14
1aname210/09/2020 09:37:14

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.27 20:24:06