1

For my ASP.NET web application, I'm currently using Automapper to map from models (DTOs) -> view models. My view models have all string properties, because I'm using Mustache, a logic-less template engine.

I'm exposing an API to my website (via JSON, etc.), and what I'd like to do is perform the following mapping:

Model -> Base ViewModel -> Web ViewModel

Then, "Base ViewModel" can be serialized for my API (eg. with numerical values for currency). From there, I'll do a simple mapping for my "Web ViewModel" (eg. with formatted currency value strings, links, etc).

Problem is, I can't seem to get this to work. Defining the Model -> Base ViewModel mapping and Base ViewModel -> Web ViewModel mappings seperately isn't enough it seems to get my Web ViewModel, and if I explicitly add the Model -> Web ViewModel mapping, Automapper just tries to map directly, skipping the intermediate step which I rely on.

Can/should Automapper be used like this? I realize that I could probably explicitly just do two sequential conversions to achieve the correct result, but I thought I'd ask here to see whether I can get Automapper to handle the conversion in one step.

mystictheory
  • 110
  • 1
  • 6

1 Answers1

0

Well, I don't believe (or to be honest I don't know how) it could be possible.

But you could try

Create your Mappings

Model.CreateMap<Model, BaseViewModel>()...
Model.CreateMap<BaseViewModel, WebViewModel>()...

and try a generic helper like this, to be changed for your needs

public static void TwoStepMapping<TSource, TIntermediate, TDest>(TSource source, TDest dest) where TIntermediate : new()
{
    Mapper.Map(Mapper.Map(source, new TIntermediate()), dest);
}

call :

TwoStepMapping<Model, BaseViewModel, WebViewModel>(model, webViewModel);
atiyar
  • 6,953
  • 6
  • 33
  • 67
Raphaël Althaus
  • 58,557
  • 6
  • 89
  • 116