Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Automapper when property names are different

Tags:

We are using AutoMapper from Codeplex and for me the destination object has all the properties ending with 'Field', ie cityField and the source object has just city.

I can use the below code to achieve but all of the properties are just suffixed with 'Field' and there are 20 properties.

.ForMember(dest => dest.cityField, opt => opt.MapFrom(origin => origin.City));

Is there any other way to ignore 'Field' word when mapping and so that it can map without using .ForMember() 20 times?

like image 202
Miral Avatar asked Feb 02 '10 17:02

Miral


People also ask

When should I use AutoMapper?

AutoMapper is used whenever there are many data properties for objects, and we need to map them between the object of source class to the object of destination class, Along with the knowledge of data structure and algorithms, a developer is required to have excellent development skills as well.

Is AutoMapper worth using?

AutoMapper will save you writing a LOT of boring mapping code and it will probably spare you from a few nasty bugs as well. The only thing you must be aware of is that the mapping uses convensions and you really want to follow these. As long as you do that, AutoMapper is a great tool!

What is AutoMapper good for?

AutoMapper is a simple library that helps us to transform one object type into another. It is a convention-based object-to-object mapper that requires very little configuration. The object-to-object mapping works by transforming an input object of one type into an output object of a different type.


1 Answers

You can try recognizing postfixes:

Mapper.Initialize(cfg => {
    cfg.RecognizePostfixes("Field");
    cfg.CreateMap<Source, Dest>();
});

Recognizing prefixes also works local to profiles, if it's just a set of maps that this applies to.

like image 159
Jimmy Bogard Avatar answered Oct 09 '22 13:10

Jimmy Bogard