.Net

How to use AutoMapper on ASP.NET Core

What is AutoMapper?

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?

Hello and welcome to this section. Here, I will explain you how you can use a AutoMapper in Asp.Net Core using Dependency Injection.

Here are some steps:

Step 1. Install AutoMapper extension from Package Manager in your project through Nuget Package or through Package Manager Console.
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 9.0.0

Step 2. Register a service in ConfigureServices on Startup.cs.

// Startup.cs
using AutoMapper; 
public void ConfigureServices(IServiceCollection services){
    services.AddAutoMapper(typeof(Startup));
}

Step 3. Create a model and a data transfer object(DTO)

// User.cs
// The model you want to map from (Source)
public class User{
    public string Name {get;set;}
    public string Email {get;set;}
    public string Phone {get;set;}
// Constructor to initialize User
    public User(){
        Name = "codehunger";
        Email = "hungerforcode@gmail.com";
        Phone = "+9999999999";
    }
}
// UserDTO.cs
// The data transfer object you want to map to (Destination)
public class UserDTO{
    public string Name{get;set;}
    public string Email{get;set;}
    public string Phone{get;set;}
}

Step 4. Create an AutoMapping class file to register a mapping relation

// AutoMapping.cs
using AutoMapper;
public class AutoMapping : Profile
{
    public AutoMapping()
    {
        CreateMap<User, UserDTO>(); // means you want to map from User to UserDTO
        //CreateMap<Source<T>,Destination<T>>();
    }
}

Step 5. Map User to UserDTO in code.

// HomeController.cs
using AutoMapper;
public class HomeController : Controller
{
    private readonly IMapper _mapper;
    public HomeController(IMapper mapper)
    {
        _mapper = mapper;
    }
    public IActionResult GetUser()
    {
        User user = new User();
        var userDTO = _mapper.Map<UserDTO>(user);
        return View(userDTO);
    }
}

And below you will get the result like this after automapping.

var name = userDTO.Name; // name = "codehunger"
var email = userDTO.Email; // email = "hungerforcode@gmail.com"
var phone = userDTO.Phone; // phone = "+9999999999"

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button