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.

Code

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.


5 comments:

  1. Learned a lot of new things from your post!Good creation ,It's amazing blog


    .Net Online Training

    ReplyDelete
  2. Spark interact web design sydney is recruiting. check out the great new positions and apply online now

    ReplyDelete
  3. You have discussed an interesting topic that every designer to know. Very well explained with examples. Spark interact is recruiting for 2018 check out the great new positions and apply online now Visit web design sydney and upload your resume.

    ReplyDelete
  4. It's amazing blog And useful for me Thanks
    . Net Online Training

    ReplyDelete