Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In AutoMapper can you apply the same value resolver to multiple members

Tags:

c#

automapper

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()));
like image 620
Twisted Avatar asked Nov 27 '15 12:11

Twisted


People also ask

When should you not use AutoMapper?

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.

Is AutoMapper bidirectional?

The Automapper Reverse Mapping is nothing but the two-way mapping which is also called as bidirectional mapping.


1 Answers

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.

like image 115
Georg Patscheider Avatar answered Nov 14 '22 23:11

Georg Patscheider