AutoMapper

AutoMapper is an object-object mapper which allows you to solve issues with mapping the same properties from one object of one type to another object of another type. For example, mapping a heavy entity Customer object to the CustomerDTO could be done with AutoMapper automatically.

Introduction

AutoMapper is an object-to-object mapper, which allows you to solve issues with mapping of the same properties in one object of one type to another object of another type. For example, mapping a heavy entity Customer object to the CustomerDTO could be done with AutoMapper automatically.

We have our domain model which has a Customer entity, and we are going to show Customers in a DataGrid, and for that, we need a much lighter object CustomerViewItem, a list of which is bound to a grid.

As you see, there are four lines of code which just copy the values from one object to another. It could also be that you will need to show up to 10-15 columns in your grid. What then?

Would you like to have something that will do mapping from Customer to the CustomerViewItem 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.

AutoMapper (The Solution)

From the AutoMapper CodePlex web page, we can see that "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. What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper's established conventions, almost zero configuration is needed to map two types." So, in other words, it provides the solution for our problem.

Get Started

To get started, go and download it here. It is a standalone assembly, so you should not have difficulties including a reference to it in your project.

In order to ask AutoMapper to do the dirty work instead of me, we need to add this line somewhere in the start of our code execution:

Mapper.CreateMap<Customer, CustomerViewItem>();

Once we have that, we are done, and we can use this code to get our mapped object:

And to prove that all values have been mapped, take a look at this picture:

More Complex Example 1 (Custom Map)

So far, we know all about doing an extremely simple mapping. But, what if we need something more complex, for example, CustomerViewItem should have FullName, which consists of the first and last names of Customer?

After I added public string FullName { get; set; } to CustomerViewItem and run my application in Debug mode, I got a null in the property. That is fine, and is because AutoMapper doesn't see any FullName property in the Customer class. In order to "open its eyes", all you need to do is to change our CreateMap process a bit:

More Complex Example 4 (Custom Formatters)

What if I want AutoMapper to use my custom formatting of DateTime instead of just using ToString, when it does a mapping from a DateTime to a String property? Let's say, I want to use the ToLongDateString method to show the birth date in a different fashion.

It looks like manual mapping is 7 times faster than automatic. But hey, it took 2 secs to map hundred thousands of customers.

It is one of the situations where you should decide if the performance is so critical for you or no. I don't think that there are a lot of cases when you really need to choose manual mapping exactly because of performance issue.

Points of Interest

I hope my article was interesting to read and that it gave you ideas for how you can utilize this new feature called "AutoMapper".

Share

About the Author

I'm very pragmatic and self-improving person. My goal is to become successful community developer.
I'm young and love learning, these are precondition to my success.

Currently I'm working in dedicated Ukrainian outsourcing company SoftServe as .NET developer on enterprise project. In everyday work I'm interacting with lot of technologies which are close to .NET (NHibernate, UnitTesting, StructureMap, WCF, Win/WebServices, and so on...)

hello, i m very impressed with this work as everybody else, congratulations.
i have a question though, i have a class named "Person" that has 12 properties which inherits a class called "SettingProperties" that has only 10 properties all of which are retrieved from an XML file using de-serialize function, of course the XML file is formatted to contain only 10 properties, thats why i use List<settingproperties> to hold its rows or elements.
after retrieving the XML properties into the List<settingproperties> successfully i m facing trouble now pushing these elements into the List<person> obviously because of the properties number variation.
so my question is
is there anyway to map SettingProperties data and fit them into the Person?
i find the Lambda expression of fetching each data into the Person is tedious and not so efficient. thats why i tried to give the AutoMapper a shot, but seems to fail at mapping them together.
if there is no way to do so, i will just refer to using the Lambda expression and just nullify the Person extra fields/properties.

First of all, i really appreciate your efforts, a fantastic article on automapper. As i'm a novice of automapper, i would like to know how we can handle the relations if we have a list of values referencing to some other class. For example, we've defined StudentDTO (data transfer object class) for Student (Entity class) and if this class contains reference to list of values to courses class (i.e. IList < Courses > ), how we can handle this in automapper?

The results of testing 100,000 records was roughly the same (almost worse in fact).

What I did find interesting that with a smaller (in my opinion - more reasonably sized) record set do the same test. In each scenario manual mapping still out performed the automapper, but it was much more comparable.

For example, when I tested 1,000 records automapper took 18 milliseconds to 0 for manual. Even with 10,000 records it took automapper 112 milliseconds compared to 1 millisecond.

As I summarized, in most scenarios (1000 records or less) I can live with the slight speed hit to save 10-20 lines of code per mapping

The main issue is that AutoMapper has a very high setup cost - typically 0.5 sec on my computer. After that it is quite quick, especially on LINQ projections which are cached.

One way round this in production systems is to set up all the mappings, which are held in static storage, at startup. On a web site, which is normally held in a suspended state between calls, this makes a big difference.

You might like to look at Jimmy Bogard's article on Analyzing AutoMapper performance. Its a bit old and doesn't represent the current version of AutoMapper, but its interesting to see Jimmy's thoughts.