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

如何用AutoMapper将SourceParent映射为List<Destination>并关联父ID?

Can I create a mapping rule for merging Source objects into List?

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:

  1. The base SourceChild → Destination map handles matching ChildId and OtherProperty automatically (no manual configuration needed since their names are identical).
  2. The SourceParent → List<Destination> map first converts the Childs collection to a list of Destination objects, then uses AfterMap to iterate over the result and set each SourceParentId to the parent's Id.

Verification:

After running this code, every item in the destination list will have:

  • SourceParentId = 1 (matching the parent's Id)
  • Correct ChildId and OtherProperty values copied from the corresponding SourceChild

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:53:39