AutoMapper
AutoMapper is a great tool for mapping objects from a type to another. Their own description goes like this:
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.
I am new to the AutoMapper myself, have been using it for only few weeks now. Mainly just learning the syntax and the basics, but still it has been proving to be a very valuable. Basics are really easy, and it saves a lot of time. You can do quite complex mappings with it, and the simple stuff it almost handles automatically, best of all the mapping configuration is looking elegant and effective.
I provided a small example just to show you how to get stated. We have two classes that needs to be mapped, a entity class, Book and DTO class BookDTO, can’t get any simpler.
public class Book
{
public int Author { get; set; }
public string Title { get; set; }
public string Plot { get; set; }
public int Pages { get; set; }
}
public class BookDTO
{
public int Author { get; set; }
public string Title { get; set; }
public string Plot { get; set; }
public int Pages { get; set; }
}
They have the same properties so this will map very easily. This kind of situations you can just use the DynamicMap which AutoMapper is providing. Map the BookDTO to Book:
Book book = Mapper.DynamicMap<Book>(bookDto);
And the other way around:
BookDTO bookDto = Mapper.DynamicMap<BookDto>(book);
That’s how simple it is. AutoMapper is doing all the hard work for you.