“AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another. This type of code is rather dreary and boring to write, so why not invent a tool to do it for us?” - Automapper.org
Pretty sure you’ve seen or even tried using this kind of code scenario.
CustomerDto.cs
public class CustomerDto {
public int CustomerId {get;set}
public string Firstname {get;set}
... (let's say you have many properties)
}
And you want to map it to your model class.
Customer.cs
public class Customer {
public int CustomerId {get;set}
public string Firstname {get;set}
...
}
What you usually do is manually do this:
public void ManuallyMap(CustomerDto dto){
var customer = new Customer{
CustomerId = dto.CustomerId,
Firstname = dto.Firstname,
... so on and so forth.
}
}
Make sure you’ve already created or you have existing ASP.NET Core project (MVC or Web API).
1.1 Open the terminal and execute the command or open Nuget Package Manager. Look for this package. AutoMapper.Extensions.Microsoft.DependencyInjection

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection
This is an AutoMapper extensions for ASP.NET Core project.
I named this class AutoMapperProfile.cs
. You can map multiple dtos & model class in there.
I include this class inside my “Helpers” folder but it depends on you where do you want to store this class file.
using AutoMapper;
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<CustomerDto, Customer>();
}
}
Add the automapper in the constructor & register the AutoMapper service in the ConfigureServices
method.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Mapper.Initialize(cfg =>
{
cfg.AddProfile<AutoMapperProfile>();
});
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
...
// add Automapper
services.AddAutoMapper();
...
}
}
Inject first the IMapper
in the class constructor.
public class CustomerService
{
private readonly IMapper mapper;
public CustomerService(IMapper mapper)
{
this.mapper = mapper;
}
public Customer CustomerDtoToCustomer(CustomerDto customerDto)
{
return mapper.Map<Customer>(customerDto);
}
public CustomerDto CustomerToCustomerDto(Customer customer)
{
return mapper.Map<CustomerDto>(customer);
}
}
As you see from above, it will automatically map based on their property. It’s easy so try it on your future or existing projects.
If you have some questions or comments, please drop it below 👇 :)
