w00
w00

Reputation: 26812

Use default mappings with AutoMapper

I'm using AutoMapper to map a set of Models to ViewModels. It all works fine, but i have to keep doing one thing over and over again for every model/viewmodel that i create. I have to map a certain attribute from (for example) String to Int.

So my mapping now looks something like this:

Mapper.CreateMap<ModelOne, ModelOneViewModel>()
    .ForMember (d => d.SomeProperty, opt => opt.ResolveUsing(t => Convert.ToString(t.SomeProperty)));

Mapper.CreateMap<ModelOneViewModel, ModelOne>()
    .ForMember (d => d.SomeProperty, opt => opt.ResolveUsing(t => Convert.ToInt32(t.SomeProperty)));

Mapper.CreateMap<ModelTwo, ModelTwoViewModel>()
    .ForMember (d => d.SomeProperty, opt => opt.ResolveUsing(t => Convert.ToString(t.SomeProperty)));

// ... etc

Is there a way to tell automapper that it should always map SomeProperty to a String when it maps from my Models class to my ViewModels class?

And vice versa, is it then possible to tell automapper to always map the property SomeProperty back to an Int32 when it maps from ViewModels back to Models?

Upvotes: 3

Views: 5356

Answers (1)

Patryk Ćwiek
Patryk Ćwiek

Reputation: 14328

Per your comment request, the Custom Type Converters may come in handy in your case.

I don't have any additional information for now, good thing the mentioned article looks like it's explaining things quite well.

Upvotes: 1

Related Questions