You need to enable JavaScript to run this app. ASP.NET Core中使用AutoMapper将嵌套列表DTO映射为扁平表实体的实现
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core中使用AutoMapper将嵌套列表DTO映射为扁平表实体的实现

AutoMapper DTO到数据库实体映射实现

前置准备

首先安装对应NuGet包:

  • AutoMapper
  • AutoMapper.Extensions.Microsoft.DependencyInjection

因为你的DTO和数据库实体类名均为Part1,建议使用别名区分避免命名冲突,示例如下:

// 引用时替换为你实际的命名空间
using DtoPart1 = YourProjectNamespace.Dto.Part1;
using EntityPart1 = YourProjectNamespace.DatabaseEntity.Part1;

映射规则配置

创建继承自Profile的映射配置类,根据你的业务场景二选一即可:

using AutoMapper;

public class CustomMappingProfile : Profile
{
    public CustomMappingProfile()
    {
        // 场景1:DTO的Value集合仅存1条数据,映射为单条数据库实体
        CreateMap<DtoPart1, EntityPart1>()
            .ForMember(dest => dest.Value1, opt => opt.MapFrom(src => src.Value.FirstOrDefault()!.Value1))
            .ForMember(dest => dest.Value2, opt => opt.MapFrom(src => src.Value.FirstOrDefault()!.Value2))
            .ForMember(dest => dest.Value3, opt => opt.MapFrom(src => src.Value.FirstOrDefault()!.Value3));

        // 场景2:DTO的Value集合存多条数据,映射为多条数据库实体(共用同一个Id)
        CreateMap<DtoPart1, List<EntityPart1>>()
            .ConvertUsing(src => src.Value.Select(v => new EntityPart1
            {
                Id = src.Id,
                Value1 = v.Value1,
                Value2 = v.Value2,
                Value3 = v.Value3
            }).ToList());
    }
}

服务注册

在ASP.NET Core的Program.cs中注册AutoMapper服务:

// 其他服务注册逻辑...
builder.Services.AddAutoMapper(typeof(CustomMappingProfile));

var app = builder.Build();
// 其余中间件配置...

使用示例

在业务代码中注入IMapper后调用即可:

public class YourBusinessService
{
    private readonly IMapper _mapper;
    public YourBusinessService(IMapper mapper)
    {
        _mapper = mapper;
    }

    public void TestMapping(DtoPart1 dto)
    {
        // 场景1调用:映射单条实体
        EntityPart1 singleEntity = _mapper.Map<EntityPart1>(dto);

        // 场景2调用:映射实体集合
        List<EntityPart1> entityList = _mapper.Map<List<EntityPart1>>(dto);
    }
}

注意事项

如果存在Value集合为空的可能,可以在映射逻辑中添加空值判断避免空引用异常,示例:
opt => opt.MapFrom(src => src.Value.FirstOrDefault()?.Value1 ?? 0)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 17:54:03