Tuesday, July 3, 2012

AutoMapper: How to use automatic mapping for copying different objects based on their property names.

As a developer you may have been experienced tedious job of coding tens of lines just to enable your software to map objects together. Sometimes you need to map auto generated classes of an ORM engine to your DTO objects and in other situations you may have coded a lot of lines just to copy and prepare objects for your MVVM-based system. Anyway I just want to say there is a simpler solution to this old programming problem: AutoMapper!

According to its website:

"AutoMapper is a convention-based object-object mapper. 100% organic and gluten-free. Takes out all of the fuss of mapping one object to another.

AutoMapper uses a fluent* configuration API to define an object-object mapping strategy. AutoMapper uses a convention-based matching algorithm to match up source to destination values. Currently, AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer."

So if you are interested and want to take a look at it, it's better to go directly to this address:  http://automapper.org/

Here is the simplest sample:

to be able to start using AutoMapper, you need to call CreateMap to let it know about mapping relationship between two of your classes:


After creating a map, you can map the real objects like the following sample:

            var user = DataAccess.GetUserByLoginName("userx");
            UserDto userDto = Mapper.Map<UserUserDto>(user);

*Later I will talk about fluent pattern.

No comments:

Post a Comment