Introduction to Automapper

Introduction

AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type.

When to use Automapper?

Here is one Sample scenario. Assume we have a domain model say a Customer entity and we are planning to show a list of Customers in a UI, for that, we need a much lighter object say CustomerViewModel, which has a list of Customer objects that can be used to bind the controls in UI layer.

Would you like to have something that will do mapping from Customer to the CustomerViewModel automatically?

Of course, you do, especially if you have another situation like mapping of heavy data objects into DTO objects which are considered to be sent though the wire.

How do I use AutoMapper?

First, you need both a source and destination type to work with. The destination type’s design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type’s members. If you have a source member called “FirstName”, this will automatically be mapped to a destination member with the name “FirstName”.

Once you have your types, and a reference to AutoMapper, you can create a map for the two types.

Mapper.CreateMap<Order, OrderDto>();

The type on the left is the source type, and the type on the right is the destination type. To perform a mapping, use the Map method.

OrderDto dto = Mapper.Map<Order, OrderDto>(order);

AutoMapper also has non-generic versions of these methods, for those cases where you might not know the type at compile time.

Where do I configure AutoMapper?

If you’re using the static Mapper method, configuration only needs to happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.asax file for ASP.NET applications. Typically, the configuration bootstrapper class is in its own class, and this bootstrapper class is called from the startup method.

Samples and DLL’s:

http://www.codeproject.com/KB/library/AutoMapper.aspx

http://automapper.codeplex.com/

Leave a Reply