首页 > 解决方案 > 覆盖 CreateMap - Automapper

问题描述

我有以下地图。所有十进制类型数字都有 2 个小数位。

CreateMap<decimal, decimal>().ConvertUsing(x => decimal.Round(x, 2, MidpointRounding.AwayFromZero));

但有时,我需要更多小数位,例如

CreateMap<T, R>.ForMember(x => x.Total, x => x.MapFrom(x => decimal.Round(x.Items.Sum(x => x.Price * x.Quantity), 3, MidpointRounding.AwayFromZero)))

是否可以在某些“CreateMap”中覆盖全局 CreateMap?谢谢

标签: c#.net-coreautomapper

解决方案


One option is that when you call the mapper.Map, you can provide options that override the current map profile using the inline mapping like so.

_mapper.Map(T, R, opt => opt.ConfigureMap().ForMember(x => x.Total, x => x.MapFrom(x => decimal.Round(x.Items.Sum(x => x.Price * x.Quantity), 3, MidpointRounding.AwayFromZero)));

推荐阅读