如何用AutoMapper将SourceParent映射为List<Destination>并关联父ID?
Absolutely, this requirement is totally feasible with AutoMapper! Your current code maps the Childs collection from SourceParent to List<Destination>, but it misses setting the SourceParentId on each Destination item. Let's fix that with a proper mapping configuration.
Here's the corrected approach:
We'll use two mapping configurations: one for base property matching between SourceChild and Destination, and another to handle the parent-to-collection mapping while propagating the parent's Id to each child's SourceParentId.
// Initialize AutoMapper with the correct mappings Mapper.Initialize(cfg => { // AutoMapper automatically matches properties with identical names, so this base map is straightforward cfg.CreateMap<SourceChild, Destination>(); // Map SourceParent to List<Destination>, then set the SourceParentId for each item cfg.CreateMap<SourceParent, List<Destination>>() // First, map the Childs collection to the Destination list .MapFrom(src => src.Childs) // After initial mapping, populate SourceParentId using the parent's Id .AfterMap((parent, destinationList) => { foreach (var destItem in destinationList) { destItem.SourceParentId = parent.Id; } }); // Keep your existing validation setting if needed cfg.ValidateInlineMaps = false; }); // Test the mapping var parent = new SourceParent { Id = 1, Childs = new List<SourceChild> { new SourceChild { ChildId = 12, OtherProperty = "prop1" }, new SourceChild { ChildId = 13, OtherProperty = "prop2" }, new SourceChild { ChildId = 14, OtherProperty = "prop3" }, } }; List<Destination> destination = Mapper.Map<SourceParent, List<Destination>>(parent);
What this does:
- The base
SourceChild→Destinationmap handles matchingChildIdandOtherPropertyautomatically (no manual configuration needed since their names are identical). - The
SourceParent→List<Destination>map first converts theChildscollection to a list ofDestinationobjects, then usesAfterMapto iterate over the result and set eachSourceParentIdto the parent'sId.
Verification:
After running this code, every item in the destination list will have:
SourceParentId = 1(matching the parent's Id)- Correct
ChildIdandOtherPropertyvalues copied from the correspondingSourceChild
This approach is clean, readable, and fully leverages AutoMapper's capabilities to handle the object-to-collection mapping while maintaining the parent-child relationship.
内容的提问来源于stack exchange,提问作者Gonzalo Lorieto

