In this blog, we are going to see what AutoMapper in .NET core is, as well as what problems it solves, how to use AutoMapper, the AutoMapper ForMember method, the AutoMapper ReverseMap method, and Conditional Mappings.
What is AutoMapper?
AutoMapper is a simple C# library that transforms one object type to another object type. This means that it’s a mapper between two objects. AutoMapper is the convention-based object-to-object mapper. It maps the properties of two different objects by transforming the input object of one type to the output object of another type.
How to add AutoMapper?
The first step to add AutoMapper is to install the corresponding NuGet package in the Package Manager console using the command “Install-Package Automapper.Extensions.Microsoft.DependencyInjection”. This command will install all AutoMapper Packages.
The next step configures the AutoMapper services into our application. Open startup.cs class file, add “services.AddAutoMapper(typeof(Startup))” in configure services method.
Now the AutoMapper Package has been installed and configured in our project.
How to use Automapper?
Let's take a new user model class. This class will have several properties.
Public class User {
Public int Id {
get;
set;
}
Public string FirstName {
get;
set;
}
Public string LastName {
get;
set;
}
Public string Email {
get;
set;
}
Public string Address {
get;
set;
}
Public int Age {
get;
set;
}
}
Let’s create a new user view model class, and display the user information:
Public class UserViewModel {
Public string FirstName {
get;
set;
}
Public string LastName {
get;
set;
}
Public string Email {
get;
set;
}
}
Now let’s see how to convert our domain object to a view model. We can organize our mapping configurations using the concept called Profiles.
Let’s create a new user profile class. In this class, we can create the mapping configuration inside the constructor.
Public class UserProfile: Profile // this class inherits from AutoMapper profile class
{
CreateMap < User, UserViewModel > ();
}
So, basically, we create the mapping from the User domain object to the UserViewModel. That’s it.
As soon as the application starts, AutoMapper service will scan the application and look for classes that inherit from the profile class and load their mapping configurations.
Now, let’s create new controller with the name UserController,
Public class UserController: controller {
Private readonly IMapper _mapper;
Public UserController(IMapper mapper) {
_mapper = mapper;
}
Public IActionResult Index() {
var userInfo = GetUserInfo();
var userViewModel = _mapper.map < UserViewModel > (userInfo);
return View(userViewModel);
}
Private static User GetUserInfo() {
Return new User {
Id = 1,
FirstName = “John”,
LastName = “Smith”,
Email = “john.smith @gmail.com”
}
}
} 
Join the conversation! Your thoughts help the community grow.