LogIn
I don't have account.

How to Integrate AutoMapper in asp dot net core project

DevSniper
122 Views

AutoMapper is a popular object-to-object mapping library for .NET. It simplifies the process of mapping one object to another. The primary goal of AutoMapper is to reduce the need for repetitive, manual mapping code by automating the transformation of object properties. Instead of writing code to assign each property individually, AutoMapper allows you to define mapping configurations and then it automatically maps between objects of different types based on property names and types.

This is especially useful when transferring data between layers of an application (e.g. from a Data Transfer Object (DTO) to a domain model).

Create an ASP.NET Core Project

First step of integrating AutoMapper is to have a ASP.NET Core project where you want to integirate AutoMapper. So Let's first create a webapi ASP.NET Core project

Using .NET CLI

Open a terminal and run the following commands

dotnet new webapi -n AutoMapperDemo
cd AutoMapperDemo

This will create a ASP.NET Core webapi project

Using Visual Studio

  • Open Visual Studio.
  • Go to File > New > Project
  • Select ASP.NET Core Web API
  • Write project name (e.g., AutoMapperDemo) and click Create.
  • Select the target framework (e.g. .NET 6 or later) and click Create

Install AutoMapper

Add the required NuGet packages for AutoMapper

dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection

Note :- In .NET Core, installing the AutoMapper.Extensions.Microsoft.DependencyInjection package automatically includes the AutoMapper package as a dependency. Therefore, no need to add the AutoMapper package explicitly.

Configure AutoMapper

1. Create Mapping Profile

You can create more then one Mapping Profile in single application

using AutoMapper;

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        // mapping configuration of source and destination
    }
}

2. Register AutoMapper in program.cs

you have to register all of your mapping profile

using AutoMapper;

var builder = WebApplication.CreateBuilder(args);
// Add AutoMapper : add all Mapping profile , separated 
builder.Services.AddAutoMapper(typeof(MappingProfile ),typeof(anotherMappingProfile), .....);
var app = builder.Build();

// Middleware and routes...
app.Run();

Use AutoMapper

1. Create Source and Destination Model

public class SourceModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class DestinationModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

2. Configure in Mapping Profile

if you want to map one object to another then you have to add rules in mapping profile. AutoMapper will automatically map same name and data type(same data type casting AutoMapper do automatically)

using AutoMapper;

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<SourceModel, DestinationModel>();
    }
}

3. Useing AutoMapper in files

Now , After creating source and destination models and configured them into profile, you can map source model object into destination model object with the help of AutoMapper within your application

For example, Let's map the source model object to the destination model object within a controller

using AutoMapper;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/example")]
public class ExampleController : ControllerBase
{
    private readonly IMapper _mapper;
    public ExampleController(IMapper mapper)
    {
        _mapper = mapper;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var source = new SourceModel { Id = 1, Name = "John Doe" };
        var destination = _mapper.Map<DestinationModel>(source);
        return Ok(destination);
    }
}

Conclusion

Integrating AutoMapper into a .NET application is an easy process that simplifies object mapping and reduces boilerplate code. By following the steps in this guide, you can set up AutoMapper to efficiently map between different object types and customize the mappings as needed for your application.