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

AutoMapper如何将带子列表的源对象映射为每个元素含源属性的目标列表

AutoMapper映射配置解决方案

你可以通过以下两种常用方式实现需求,两种方案均可以复用你已经配置好的SourceSetting到DestinationSetting的映射规则:

方案1:配置全局Source到目标列表的映射规则(推荐)

直接在AutoMapper的Profile配置中新增Source到List<DestinationSetting>的类型转换规则,一次配置后可以全局直接使用:

public class YourProfile : Profile
{
    public YourProfile()
    {
        // 保留你原有已配置的映射
        CreateMap<SourceSetting, DestinationSetting>();
        
        // 新增Source到目标列表的自定义转换规则
        CreateMap<Source, List<DestinationSetting>>()
            .ConvertUsing((source, _, context) => 
            {
                return source.Settings.Select(item => 
                {
                    var destItem = context.Mapper.Map<DestinationSetting>(item);
                    destItem.PersonID = source.PersonID;
                    return destItem;
                }).ToList();
            });
    }
}

使用方式:

// 直接传入Source对象即可得到目标列表
List<DestinationSetting> result = mapper.Map<List<DestinationSetting>>(sourceObj);

方案2:通过映射上下文传值实现

如果仅需要临时使用该映射逻辑,不想新增全局映射规则,可以通过AutoMapper的上下文Items参数传递PersonID:

  1. 先修改原有SourceSetting到DestinationSetting的映射配置,增加PersonID的赋值逻辑:
CreateMap<SourceSetting, DestinationSetting>()
    .ForMember(dest => dest.PersonID, opt => opt.MapFrom((_, _, _, context) => context.Items["PersonID"]));
  1. 映射时传入PersonID参数:
List<DestinationSetting> result = mapper.Map<List<DestinationSetting>>(sourceObj.Settings, opt => 
{
    opt.Items["PersonID"] = sourceObj.PersonID;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:36:03