DEV Community

ibenge Uforo
ibenge Uforo

Posted on • Updated on

Entry-5: Automapper: Streamlining Object-to-Object Mapping for C# Developers

Working with DTOs can be tedious, but working with AutoMapper makes it a breeze.

in simple terms, it is an object-to-object mapper. This means mapping the fields of one object to another ie.

Mapping...


class object1 {
  field1,
  field2
 }

// to 

class object2 {
  field1,
  field2
}

Enter fullscreen mode Exit fullscreen mode

why do we need it, you might ask. We need AutoMapper when we have a lot of fields and we want to create a data transfer object that returns only the essentials the client needs. In this case, manually instantiating both items and appending to both is time-consuming. Instead, with the help of AutoMapper, we can easily map the fields.

see visual example below;

say we have a user model


public class User {

 public string FirstName {get; set;}
 public string LastName {get; set;}
 public string PhoneNumber {get; set;}
 public string Email {get; set;}
 public string Pin {get; set;}
 public string Password {get; set;}
 public int NoseSize {get; set;}
 public int HeadSize {get; set;}
 public int ToeSize {get; set;}

}

Enter fullscreen mode Exit fullscreen mode

and then a DTO.


public class UserDTO {

 public string FirstName {get; set;}
 public string LastName {get; set;}
 public string PhoneNumber {get; set;}
 public string Email {get; set;}
 public int NoseSize {get; set;}
 public int HeadSize {get; set;}
 public int ToeSize {get; set;}

}

Enter fullscreen mode Exit fullscreen mode

In order to make use of the DTO, we append the values such as.


UserDTO userDTO = new(){

FirstName = user.FirstName,
LastName = user.lastName,
PhoneNumber = user.PhoneNumber,
...
// You get the drift.

}

Enter fullscreen mode Exit fullscreen mode

We would be manually appending to each field. but with the help of AutoMapper, it would be simple as

// After the setup of automapper
var userMap = autoMapper<Destination>(source); 
// and we are done!
}

Enter fullscreen mode Exit fullscreen mode

So, the TLDR: it removes the manual task of working with Data Transfer Objects (DTOs).

Setup.

We would be making use of Dependency Injection for the task, enabling us make use of the automapper config and interface any where in our app.

Steps

  • Install the Automapper package with dependency Injection (D.I).

automapper dependency injection package

  • Create a source and Destination. source here means what we are mapping from and destination means, what would the final result be.

Using our example from above, the source is our user model and destination is our UserDTO

  • Create an assembly which extends the automapper profile containing the configuration for each mapping.

ie.

using System;
using AutoMapper;
using lastbank.Database;
using lastbank.DTO;
namespace lastbank.Configuration
{
    public class AutoMapperCfg: Profile
    {
        public AutoMapperCfg()
        {
            CreateMap<APIUser, UserDTO>().ReverseMap();
            CreateMap<APIUser, CreateUserDTO>().ReverseMap();
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

A twist above with the reverseMap, this enables us map both directions.

  • Add the automapper service to the DI container within your program.cs file with
services.AddAutoMapper(typeof(AutoMapperCfg));
Enter fullscreen mode Exit fullscreen mode
  • Access through your DI method
  • Invoke Object.
            var userMap = _mapper.Map<Destination>(Source);

Enter fullscreen mode Exit fullscreen mode

Voila!

Above we covered the basics of how to install and configure AutoMapper, as well as its more advanced features with D.I.

We've seen how AutoMapper can make mapping between object types easier, more concise, and less prone to errors. It's a powerful tool for any C# developer who works with complex/non-complex object hierarchies, of which it significantly reduces the time and effort spent on manual mapping. With its continuously evolving features, AutoMapper remains an exciting and valuable tool for developers.

... Also, checkout cool alternatives such as Mapster.

Resource;

Other Links

Top comments (0)