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

如何通过Mapster接口代码生成实现IEnumerable到IDictionary的正确映射?

问题描述

我想把这段手动映射代码:

var group = new Group {
    Participants = family.Children.ToDictionary(child => $"{child.LastName}, {child.FirstName}", child =>
        new Participant
        {
            Class = child.Age,
        })
};

替换为使用Mapster框架的实现:var camp = new UnitMapper().Map(family),但不知道该如何配置才能让Dictionary的映射正确执行。

当前我的代码如下:

[Mapper]
public interface IUnitMapper {
    Group Map(Family family);
}

public class MappingRegistration : IRegister {
    public void Register(TypeAdapterConfig config) {
        config.NewConfig<Family, Group>()
            .Map(to => to.Participants, from => from.Children)
            ;
        
        config.NewConfig<Child, Participant>()
            .Map(to => to.Class, from => from.Age)
            ;
    }
}

public class Family {
    public IEnumerable<Child> Children { get; set; }
}

public class Child {
    public string FirstName { get; init; }
    public string LastName { get; init; }
    public int Age { get; init; }
}

public class Group {
    public IDictionary<string, Participant> Participants { get; set; }
}

public class Participant {
    public int Class { get; set; }
}
解决方案

你需要在Family到Group的映射配置中,明确指定Dictionary的键生成规则,同时结合已有的Child到Participant的映射配置。修改MappingRegistration类的Register方法即可:

public class MappingRegistration : IRegister {
    public void Register(TypeAdapterConfig config) {
        // 保留Child到Participant的映射配置
        config.NewConfig<Child, Participant>()
            .Map(to => to.Class, from => from.Age);
        
        // 修改Family到Group的映射,指定Participants的转换逻辑
        config.NewConfig<Family, Group>()
            .Map(to => to.Participants, from => 
                from.Children.AdaptToDictionary(
                    child => $"{child.LastName}, {child.FirstName}", // Dictionary的键生成规则
                    child => child.Adapt<Participant>() // 复用已配置的Child到Participant映射
                )
            );
    }
}

说明

  • AdaptToDictionary是Mapster提供的扩展方法,可直接将IEnumerable转换为Dictionary,需传入键的生成表达式和值的转换表达式。
  • 由于已提前配置Child到Participant的映射规则,child.Adapt<Participant>()会自动复用该规则,无需重复编写Class = child.Age的逻辑。
  • 完成配置后,调用new UnitMapper().Map(family)即可生成和手动映射完全一致的Group对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:47:27