Ritmo2k
Ritmo2k

Reputation: 1021

More efficient custom map configuration

I am using AutoMapper 6.2.2 to convert a view model into a dto model. The view model has 2 matching fields and a single unmatched field which can be converted to 7 other fields. The issue is that the unmatched field is parsed with a static method that produces all 7 alternate fields. So instead of issuing ForMember for each of the 7 individual fields and calling a static conversion method each time, how can I map the source Value field to 7 destination members in one pass without instantiating it more than once?

this.CreateMap<MyViewModel, MyModel>()
    .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
    .ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description))
    .ForMember(dest => dest.FieldA, opt => opt.MapFrom(src => StaticHelper.Parse(src.Value).FieldA))
    // More instances of the same static helper unnecessarily instantiated.
    .ForMember(dest => dest.FieldG, opt => opt.MapFrom(src => StaticHelper.Parse(src.Value).FieldG));

Upvotes: 2

Views: 47

Answers (1)

NetMage
NetMage

Reputation: 26917

Using ConstructUsing you can build the initial object and map the 7 fields from the one source field via the static method and then let AutoMapper map the remaining fields or continue with ForMember to map them manually.

Upvotes: 2

Related Questions