How to use AutoMapper in ASP.NET Core

In this content, we will examine the integration and use of AutoMapper library, which allows dynamically mapping ViewModel objects with the entities modeled in Asp.NET Core applications.


First, let's start our article by explaining what the ViewModel object is.


What is ViewModel ?


It is an object in OOP structure that represents the members of a model used as a result of interaction with the user.


For example, our model plays a role as follows in a post operation made with a username and password for account login.


Model (Entity)


namespace WebApplication1.Models
{
    public class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}

AutoMapper-ViewModel_1.png

AutoMapper-ViewModel_2.png

ViewModel


namespace WebApplication1.Models.ViewModels
{
    public class VMPerson
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}

In this way, if we meet the posted object directly with the model/entity, the unrelated properties except the related properties will come with their default values. Therefore, this will not be a very useful structure. Here, we are eliminating the unnecessary properties by meeting the data received as a result of the post directly with the ViewModel object.


AutoMapper-ViewModel_3.png

In the following code snippet, we have manually transfered the data in the ViewModel to the model/entity (Person). We will leave it to the AutoMapper object which will do this automatically.

[HttpPost]
public ActionResult Create(VMPerson person)
{
    Person p = new Person()
    {
        UserName = person.UserName,
        Password = person.Password
    };

    return View();
}

We need to transfer the data in the ViewModel to the model (Person). AutoMapper performs this process automatically.


You can integrate the AutoMapper library into the project via the code below:


> Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 3.0.1

To use AutoMapper library, the relationship between the model/entity (Person) and the created ViewModel (VMPerson) must be specified.


The "Profile" class of the AutoMapper library is used for mapping. Let's create a class named PersonProfile as follows.


using AutoMapper;
using WebApplication1.Models;
using WebApplication1.Models.ViewModels;

namespace WebApplication1
{
    public class PersonProfile : Profile
    {
        public PersonProfile()
        {
            CreateMaplt;VMPerson, Person>();
            CreateMap<Person, VMPerson>();
        }
    }
}

If you pay attention to the code block above, our class named "PersonProfile", which we derive from the "Profile" abstract class.


Matches are made through the "CreateMap" method from the "Profile" class. The point you need to be aware of here is that every mapping also has its reverse situations


In the following code snippet, the AutoMapper library is defined to the application in the "ConfigureServices" method in the "Startup.cs" file.


public void ConfigureServices(IServiceCollection services)
{
    ...
	
	var mappingConfig = new MapperConfiguration(mc =>
	{
		mc.AddProfile(new PersonProfile());
	});
	IMapper mapper = mappingConfig.CreateMapper();
	services.AddSingleton(mapper);
}

Usage: _mapper is taken with "IMapper mapper" Dependency Injection in the constructor of HomeController class. The data coming from the View is transformed into the desired structure with the definitions made in PersonProfile.


private readonly IMapper _mapper;
public HomeController(IMapper mapper)
{
	_mapper = mapper;
}
[HttpPost]
public ActionResult Create(VMPerson person)
{
	Person p = _mapper.Map<Person>(person);

	return View(p);
}

AutoMapper-ViewModel_4.png