Auto mapper - object to object mapper
AutoMapper is a great utility helps developers to map their two different objects with same properties in it. It can work with any number of child node in it at any level. A big tree of object can be converted into another type of same tree structure in a single method call.
AutoMapper is an object to object mapping utility free from codeplex. This works great to map between your domain object to data transfer objects.
In your application if you have this situation this automapper can help you a lot in mapping the objects. Lets say you have business object Person and when it is stored in DB you need to pass a dto PersonDTO.
At the time of calling your database persist call you will have to convert your Person business object to PersonDTO for that you have to write something like,
var personDTO = new PersonDTO
PersonId = person.PersonId,
Name = person.Name,
Address = person.Address,
Age = person.Age,
Rank = person.Rank
What if your person object is having lots of children object like Address, and all those children are having several children in multiple level. If all the children are having 25 property then assue how much mapping code you have to do.
Same above code for converting DTO to BusinessObject needs to be done for all the objects when you get them from the DB.
So AutoMapper automatically understands the mapping and it does the mapping for you,
Code would be very simple like,
var PersonDTO = Mapper.Map
Isn't it clean, neat and slick? just a single method call will do all the mapping for you upto any level for its children too.
Here the Map() method takes what are the source and destination types and the source object as input.
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.
The source and business object names and all its properties names should be same thats the only condition that you have to make sure; otherwise there is no way to understand what to map with which property or object.
To configure auto mapper
Mapper.AssertConfigurationIsValid();//makes sure all the object's attribute are okay