HOW TO code better using AutoMapper

AutoMapper_snippetWhen you use external libraries you are forced to use their classes inside your own code. To make yourself more confident, it is wise to make your own classes simpler than external ones. Usually, in order to do this you have to do some manual code behind. AutoMapper helps you in that process by automatic mapping fields between classes and rewriting their fields. How does it work?

To start your mapping using AutoMapper you have to do two things

Firstly, you have to define the way how mapping should be carried out. The simplest example is:

[csharp]Mapper.CreateMap<Source,Destination>();[/csharp]

Next, you pass a class instance of Source class to a mapper in order to convert it into Destination class instance:

[csharp]result = Mapper.Map<Source, Destination>(source);[/csharp]

This code snippet will create the new instance of Destination class with fields rewritten from a Source class. It is important to note that the fields are mapped by their names. If the name is different, current configuration will not handle these fields and will assign a null value.

More complex usage of AutoMapper

You can imagine how many different scenarios you may experience while converting one object instance to another. The whole list of AutoMapper features is available here. Below I will show the neatest snippets. I have found AutoMapper extremely useful in changing the collection objects from one to another. Imagine, you have LLBLGEN self servicing class that reprents the collection of products – ProductsCollection class. This class implements IEnumerable and contains products – ProductEntity class. You want to map it to IList<IProduct> object. This way you hide from the external code your LLBLGEN entity classes and you limit the amount of properties in IProduct interface.

[csharp]public class ProductEntity
{
	public string ProductNumber { get; set; }
	public string DateTime { get; set; }
	public string Name{ get; set; }
}

public class IProduct
{
	public int ProductNumber { get; set; }
	public DateTime DateTime { get; set; }
	public string ProductName { get; set; }
}[/csharp]

To convert ProductEntity to IProduct you don’t need any additional classes. By the correct AutoMapper configuration you can perform your conversion pretty smoothly.

[csharp]IMappingExpression&lt;ProductEntity, IProduct&gt; mapping = Mapper.CreateMap&lt;ProductEntity, IProduct&gt;();
mapping.ForMember(dto =&gt; dto.ProductName, opt =&gt; opt.MapFrom(m =&gt; m.Name));
Mapper.CreateMap&lt;string, int&gt;().ConvertUsing(arg =&gt; Convert.ToInt32(arg));
Mapper.CreateMap&lt;string, DateTime&gt;().ConvertUsing(new DateTimeTypeConverter());[/csharp]

Now, you can convert your ProductEntity object to IProduct. In our example, we have ProductCollection class which we want to convert to IList<IProduct> object instance. AutoMapper is able to perform this conversion directly without defining additional mapping for our collection classes. Our conversion code is:

[csharp]var result = Mapper.Map&lt;ProductCollection, IList&lt;IProduct&gt;&gt;(source); //source is an instance of ProductCollection class[/csharp]

How AutoMapper converts classes to interfaces?

In the above example, you are probably curiouse what kind of class is used to create the instance of object that is behind IProduct interface. This class is called DynamicProxy and is created by use of LinFu library. This way, we don’t have to create our own classes to map ProductEntity to IProduct interface. AutoMapper creates a custom proxy class for you.

AutoMapper is a useful library that speeds up your coding

Thanks to AutoMapper I avoided creating special proxy classes to map my domain object to more simple ones. This for sure can speed up your coding a little and makes your components less vulnerable to external libraries’ changes. Share your opinion and experience with us below or meet us on Twitter: @GOYELLO.

Tags: ,

Aspire Blog Team

Aspire Systems is a global technology services firm serving as a trusted technology partner for our customers. We work with some of the world's most innovative enterprises and independent software vendors, helping them leverage technology and outsourcing in our specific areas of expertise. Our services include Product Engineering, Enterprise Solutions, Independent Testing Services and IT Infrastructure Support services. Our core philosophy of "Attention. Always." communicates our belief in lavishing care and attention on our customers and employees.

10 comments

  1. What I then want to do, rather than writing code to populate each BLL property from its DAL … it's better to configure your type maps just once per application lifetime

  2. Hi,
    yes, the configuration should be stored once per life time. To do so it should be moved to for instance Global.asax or to Bootstrapper if you use IoC Container.

  3. Well , the view of the passage is totally correct ,your details is really reasonable and you guy give us valuable informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum! http://less-accurate.com/

  4. I am also a XX fan who really like this! I also like XX, and purchase lots of it every time, like-minded friends can have a look ,we can communicate by the way~~

Comments are closed.