如何为AutoMapper配置自动映射约定:处理CurrencyId到Currency字段映射
如何配置AutoMapper自动映射约定处理CurrencyId到Currency的映射?
嘿,这个场景我太熟悉了!每次手动写那行ForMember映射确实挺烦的,AutoMapper的自定义成员配置约定正好能帮你搞定这个重复工作,不用再一遍遍写相同的映射规则。下面是具体的实现方案:
1. 编写自定义映射约定类
我们需要实现IMemberConfigurationProvider接口来定义全局的映射规则,它会自动匹配符合条件的属性对:
public class CurrencyIdToCurrencyVmConvention : IMemberConfigurationProvider { public void ApplyConfiguration(IMemberConfigurationExpression memberConfigurationExpression) { // 针对所有类型的映射,匹配目标端的Currency属性(类型为CurrencyVm) memberConfigurationExpression .CreateMap<object, object>() .ForMember( dest => dest.GetType().GetProperty("Currency"), opt => { // 检查源对象是否存在CurrencyId属性,且类型为CurrencyId var sourceCurrencyIdProp = opt.Context.SourceType.GetProperty("CurrencyId"); if (sourceCurrencyIdProp != null && sourceCurrencyIdProp.PropertyType == typeof(CurrencyId)) { // 利用AutoMapper已有的映射逻辑,将CurrencyId转换为CurrencyVm opt.MapFrom(src => opt.Context.Mapper.Map<CurrencyVm>(sourceCurrencyIdProp.GetValue(src))); } }); } }
2. 将约定注册到AutoMapper配置中
在初始化MapperConfiguration的时候,把这个自定义约定添加进去,让它全局生效:
var mapperConfig = new MapperConfiguration(cfg => { // 注册自定义的成员映射约定 cfg.AddMemberConfiguration().AddMember<CurrencyIdToCurrencyVmConvention>(); // 这里继续添加你的其他映射配置,比如领域模型到视图模型的映射 // cfg.CreateMap<OrderDomain, OrderViewModel>(); // cfg.CreateMap<ProductDomain, ProductViewModel>(); });
3. 验证配置(可选但推荐)
配置完成后,建议验证一下映射配置的有效性,提前发现潜在问题:
mapperConfig.AssertConfigurationIsValid();
额外说明
- 这个约定是全局生效的,只要你的领域模型包含
CurrencyId属性,视图模型包含Currency属性(类型为CurrencyVm),AutoMapper就会自动应用这个映射规则,无需手动编写ForMember代码。 - 如果某个特定映射需要覆盖这个全局约定,你仍然可以在该映射的配置中手动编写
ForMember,手动配置的优先级会高于全局约定。
内容的提问来源于stack exchange,提问作者Shadow
相关产品推荐
相关产品推荐

