I have some mapping code as follows
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
As you can see I am mapping multiple members using the same resolver to convert a integer to a formatted currency string. I'm doing this for the vast majority but not all members on my poco class.
All these members would map using convention based mapping if I didn't need to keep repeating these types. Its a massive amount of code to write for a simple task.
Is there any way to override the default behaviour for converting an int to a string for a single map and then do custom .ForMembers where I want something different. Such as this:
Mapper.CreateMap<CalculationQueryResult, CalculationViewModel>()
.SetDefault<int,string>(opt => opt.ResolveUsing<FormattedCurrencyInt>())
.ForMember(poco => poco.Count, x=>x.MapFrom(s => s.Count.ToString()));
If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.
The Automapper Reverse Mapping is nothing but the two-way mapping which is also called as bidirectional mapping.
You can create the default mapping as
Mapper.CreateMap<int, string>().ConvertUsing<FormattedCurrencyIntConverter>();
private class FormattedCurrencyIntConverter : TypeConverter<int, string> {
protected override string ConvertCore(int numericValue) {
return numericValue.ToString("C2"); // format here ...
}
}
But beware that this mapping rule will be applied for all integers! Overriding this rule for certain members is probably possible, but I didn't test it.
PS: I recommend to write down all mapping rules explicitly and don't rely on convention based mappings. If a property gets renamed only on one side, the convention based mapping breaks, but an explicit rule can be refactored automatically by the IDE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With