ASP.NET 4.7.1 Hosting – Mapping Similar Objects In ASP.NET Core 2.0

This post is about Automapper. As its name suggests, it will do some sort of mapping. Now, the question is, what sort of mapping? Well, this mapping is all about mapping the properties of two objects with each other. If you have worked on MVC, you must have come across the scenario, where the situation demands you to map properties of the model with the properties of ViewModel. Isn’t it a common scenario? So, one way to achieve this is to map each and every property manually with a lot of code, which in turn become very tedious when there are many properties of an object. Another major disadvantage of this approach is it’s error-prone.

Hence, Automapper came to rescue. Automapper is an object to object mapping which reduces the manual effort of mapping each property of a class with the same properties of another class. So, let’s start by writing some code and see how it works.

Step 1

First step is to add the required dependency. This can be done either by using UI or by using Nuget package console,

if you are using console to add dependency, then on successful installation of the package, the below message will be shown,

Step 2

Get ready with classes which are to be mapped. Here in this case, we have one model class and one ViewModel class as shown below,


Step 3

Create a class which will take care of all the mappings as shown below, by inheriting the profile which is defined in Automapper namespace,

Step 4

Register this MappingEntity class in Startup class under ConfigureServices method as shown below,

Step 5

Final step is to do the changes in Controller class to accomodate this mapping.

Now, as per the business requirement, the contact object declared in line number 11 can be used. That’s all about automapping.