In AutoMapper, you can apply the same value solver to multiple members

I have a display 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 map multiple members using the same resolver to convert an integer to a formatted currency string. I do this for the vast majority, but not for all members of my poco class.

All these members will be displayed using matching based matching if I don't need to repeat these types. Its a huge amount of code to write for a simple task.

Is there a way to override the default behavior to convert int to string for one card, and then execute custom .ForMembers where I want something else. For example:

 Mapper.CreateMap<CalculationQueryResult, CalculationViewModel>() .SetDefault<int,string>(opt => opt.ResolveUsing<FormattedCurrencyInt>()) .ForMember(poco => poco.Count, x=>x.MapFrom(s => s.Count.ToString())); 
+8
c # automapper
source share
2 answers

You cannot apply the same value converter to multiple elements in the manner described.

It can redefine the default mapping from int to string for all comparisons, as suggested by Georg Patcher, but it can have side effects worse than the original problem.

You will have to record the display line by line.

-one
source share

You can create a 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 be careful that this matching rule will apply to all integers! It may be possible to override this rule for certain members, but I have not tested it.

PS: I recommend writing down all matching rules explicitly and not rely on matching based on conventions. If a property is renamed on one side only, the agreement-based mapping breaks, but the explicit rule can be automatically reconfigured using the IDE.

+4
source share

All Articles