Twisted
Twisted

Reputation: 3432

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

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()));

Upvotes: 8

Views: 2378

Answers (2)

Twisted
Twisted

Reputation: 3432

You cannot apply the same value resolver to multiple members in they way described.

It can override the default mapping from int to string for all mappings, as suggested by Georg Patscheider but this is likely to have side effects worse than the original problem.

You will have to write out the mapping line by line.

Upvotes: 0

Georg Patscheider
Georg Patscheider

Reputation: 9463

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.

Upvotes: 4

Related Questions