在AutoMapper中,可以将相同的值解析程序应用于多个成员
本文关键字:程序 应用于 成员 AutoMapper | 更新日期: 2023-09-27 18:24:56
我有一些映射代码如下
Mapper.CreateMap<CalculationQueryResult, CalculationViewModel>()
.ForMember(poco => poco.NomineeFee,
opt => opt.ResolveUsing<FormattedCurrencyInt>()
.FromMember(m => m.NomineeFee))
.ForMember(poco => poco.TotalContributions,
opt => opt.ResolveUsing<FormattedCurrencyInt>()
.FromMember(m => m.TotalContributions))
.ForMember(poco => poco.EquityInjection,
opt => opt.ResolveUsing<FormattedCurrencyInt>()
.FromMember(m => m.EquityInjection))
// ... SNIP Lots more members mapped with Formatted Currency Resolver
正如您所看到的,我正在使用同一个解析器映射多个成员,以将整数转换为格式化的货币字符串。我这样做是为了我的poco课程中的绝大多数成员,但不是所有成员。
如果我不需要不断重复这些类型的话,所有这些成员都会使用基于约定的映射进行映射。为一项简单的任务编写大量的代码。
有没有任何方法可以覆盖将int转换为单个映射的字符串的默认行为,然后进行自定义。对于我想要不同内容的成员。例如:
Mapper.CreateMap<CalculationQueryResult, CalculationViewModel>()
.SetDefault<int,string>(opt => opt.ResolveUsing<FormattedCurrencyInt>())
.ForMember(poco => poco.Count, x=>x.MapFrom(s => s.Count.ToString()));
您可以将默认映射创建为
Mapper.CreateMap<int, string>().ConvertUsing<FormattedCurrencyIntConverter>();
private class FormattedCurrencyIntConverter : TypeConverter<int, string> {
protected override string ConvertCore(int numericValue) {
return numericValue.ToString("C2"); // format here ...
}
}
但请注意,此映射规则将应用于所有整数!对于某些成员来说,覆盖这个规则可能是可能的,但我没有测试它
PS:我建议明确地写下所有映射规则,不要依赖于基于约定的映射。如果属性只在一侧被重命名,则基于约定的映射会中断,但IDE可以自动重构显式规则。
不能按照描述的方式将同一个值解析程序应用于多个成员。
正如Georg Patscheider所建议的那样,它可以覆盖所有映射从int到string的默认映射,但这可能会产生比最初问题更严重的副作用。
你必须一行一行地写出地图。