Adafyn kuulumisia

Automapper For Dummies

Today I was mentoring a younger dev, and he asked about how to handle data mapping between model and DTO classes. I advised him to use Automapper, which I find to be a quite simple solution for rather time consuming mapping task. I just couldn’t find any decent guide for VB.NET & Automapper start-up, so I decided to write my own.

Add NuGet package

Right Click Project in Solution Explorer and select Managet NuGet packages…
Click Browse, type Automapper in search box, select it and click Install.


For this example I created two classes which are mapped: Person and PersonDTO

Then into fun part. First create instance of MapperConfiguration. This contains all the mappings that are used in this project. I could also use static Mapper.Initialize method, but I like the instance way more. 
MapperConfiguration takes in a method, so I have defined it as a lambda expression. CreateMap method calls defines a mapping between Person and PersonDTO. If I wanted to add some special rules for mapping, this method would be the right place to do it.
The actual mapping is simply done by calling Map method and telling mapper what type of data to take in.

And here’s the result:

Using Automapper is very easy and I hope this VB.NET example is useful to get started with it.