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

AutoMapper单源多目标映射问题:Source2映射至Dest1含Dest3列表

Fixing AutoMapper Mapping from Source2 to Dest1 with List

Your current mapping issue stems from a type mismatch: you’re trying to assign a single Source2 instance directly to Dests3, which is a List<Dest3> property. AutoMapper can’t automatically convert a single object to a list, so we need to adjust that part of the configuration.

Here’s the corrected approach:

  1. Keep your existing Source2 → Dest3 mapping (this part is already correct, since their properties align perfectly):

    CreateMap<Source2, Dest3>();
    
  2. Update the Source2 → Dest1 mapping to wrap the mapped Dest3 in a list for the Dests3 property. Additionally, since Dest1 has prop1, prop2, and prop3 that don’t exist on Source2, we need to ignore those members to avoid mapping errors:

    CreateMap<Source2, Dest1>()
        .ForMember(dest => dest.Dests3, opt => 
            // Map the Source2 to Dest3 (using our existing mapping) and wrap it in a list
            opt.MapFrom(src => new List<Dest3> { src }))
        // Ignore any Dest1 properties that don't have a matching source in Source2
        .ForAllOtherMembers(opt => opt.Ignore());
    

Why this works:

  • When you pass src (a Source2 instance) into the list, AutoMapper uses the pre-configured Source2 → Dest3 map to convert it automatically.
  • The ForAllOtherMembers call tells AutoMapper not to throw errors for prop1, prop2, and prop3 since there’s no corresponding data in Source2 to map from. If you later add matching properties to Source2, you can remove this line and AutoMapper will handle those mappings automatically.

Testing this should now correctly map your Source2 instance to a Dest1 where Dests3 contains a single Dest3 populated with prop7 and prop8 from the source.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:02:52