DEV Community

Oyekunle Oyewusi
Oyekunle Oyewusi

Posted on

C# Automapper in .NET 6 

An automapper is a simple library used to map one object type into another. The library uses reflection mechanism to dynamically bind types and property names together. There are some properties that require manual mapping based on their names and types.
 

Let's get started
Step 1: Install the library
You can add automapper library to your .net project using CLI Or adding it from your nugget package.
CLI command:
> dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection
Visual studio:
> Install-package AutoMapper.Extensions.Microsoft.DependencyInjection

Step2: Configuration (I)
In .NET 5, you can add Automapper inside your startup.cs. In .NET 6, we don't have startup.cs class by default. You can now add Automapper library directly in program.cs class
Snippet Code:

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); 
Enter fullscreen mode Exit fullscreen mode

Step3: Configuration (II)
We need to write a class that inherits from the automapper library's Profile class and include the configuration in the constructor.

 public class UserProfile:Profile
    {
       public UserProfile()
        {
         //source mapping to destination
            CreateMap<User, UserDTO>().ForMember(des=>des.UserId, opt=>opt.MapFrom(src=>src.Id));

       } 
    }


Enter fullscreen mode Exit fullscreen mode

Step 4:
The code implementation, the project starts working from the program.cs file, then moves to the class where Automapper Profile is being inherited before the controller class. The IMapper interface from the library is injected into the controller class and the mapping is done on the method that requires it.

  ("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserRepo _repository;
        private readonly  IMapper _mapper ;
        public UserController(IUserRepo repository, IMapper mapper)
        {
            _mapper = mapper;
            _repository = repository;
        }
        [HttpGet]
         public ActionResult<IEnumerable<UserDTO>>  GetAllUsers()
         {

          var userLists=_repository.GetAllUsers();
          //Mapping Here Source (User) to Destination
          return Ok(_mapper.Map<IEnumerable<UserDTO>>(userLists) );
          }
      }

Enter fullscreen mode Exit fullscreen mode

The major benefits:
As it uses conventions to determine default mappings, it should significantly reduce the amount of code you have to write compared to manual mapping. When the properties of your classes are conventionally aligned (types and names), your mapping configuration will be easy.
Image description
Using a predefined extension method (Reversed()), Automapper can be configured to map in both directions.

 public class UserProfile:Profile
    {
       public UserProfile()
        {
         //source mapping to destination
            CreateMap<User, UserDTO>().ForMember(des=>des.UserId, opt=>opt.MapFrom(src=>src.Id)).ReverseMap();

       } 
    }

Enter fullscreen mode Exit fullscreen mode

Conclusion
The Automapper is a useful and straightforward tool for mapping one class to another. It reduces the number of codes and makes clearer codes.
I hope you found the material useful. We'll cover more advanced AutoMapper topics, including the CQRS pattern and microservices, in a future post.
Let's connect LinkedIn

Top comments (0)