AutoMapper单源多目标映射问题:Source2映射至Dest1含Dest3列表
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:
Keep your existing
Source2→Dest3mapping (this part is already correct, since their properties align perfectly):CreateMap<Source2, Dest3>();Update the
Source2→Dest1mapping to wrap the mappedDest3in a list for theDests3property. Additionally, sinceDest1hasprop1,prop2, andprop3that don’t exist onSource2, 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(aSource2instance) into the list, AutoMapper uses the pre-configuredSource2→Dest3map to convert it automatically. - The
ForAllOtherMemberscall tells AutoMapper not to throw errors forprop1,prop2, andprop3since there’s no corresponding data inSource2to map from. If you later add matching properties toSource2, 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

