This post is about using Automapper in ASP.NET Core project. AutoMapper is an object-object mapper which allows you to solve the problem of manually mapping each property of a class with the same properties of another class. Before AutoMapper, if you want to map properties of one object to another, you have manually assign each of the property objects, it will hard and error-prone if an object got lot of properties. If you are a MVC developer most of the time you manually map model objects with viewmodel objects. AutoMapper helps to do it in clean and readable way. For using AutoMapper, first you need to set the mapping classes in AutoMapper, you can use
CreateMap method for this. To for map classes, you can use
So in ASP.NET Core, first you need to include AutoMapper in the project.json file as a dependency. Once you did that run
dotnet restore to download AutoMapper. Once AutoMapper added to the project, you need to configure the mapping. You can do it using either in
ConfigureServices() method. Or you can create a profile class, where you can add all the mappings and use it in
ConfigureServices() method. In this post I am mapping User and UserViewModel class. Here is the Model and ViewModel classes.
And here is the code in
You can map the classes using Map method of Mapper object. To use Mapper object in controllers, you can inject it using ASP.NET Core dependency injection.
This is the screenshot of mapping using Automapper.
Here is the profile class implementation, which quite similar to current implementation except all the mappings will be inside this class.
And you can use it like this in the Startup class.
And you need to use
Automapper package in project.json as dependency.
Happy Programming :)