Entry-5: Automapper: Streamlining Object-to-Object Mapping for C# Developers
Tags: dotnetcore, dotnet, automapper, productivity
Published: 2023-02-18 22:13:10



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...

```c#

class object1 {
  field1,
  field2
 }

// to 

class object2 {
  field1,
  field2
}

```

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

```c#

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;}

}

```

and then a DTO.


```c#

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;}

}

```

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


```c#

UserDTO userDTO = new(){

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

}

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

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

```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nh91lnaq6aw2ja9gaonz.png)

- 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.

```c#
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();
        }
	}
}

```
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 
```c#
services.AddAutoMapper(typeof(AutoMapperCfg));
```

- Access through your DI method
- Invoke Object.

```
            var userMap = _mapper.Map<Destination>(Source);

```

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;

- [Automapper](https://docs.automapper.org/en/latest/Getting-started.html) 
- [Trevoir williams - API Development](https://www.youtube.com/watch?v=kFzkvAtni9A&list=PLUl9BcvgsrKYa9mUygO9lIGow-1GaNWqs&index=7)


**Other Links**

- **Twitter**: [@benny_wayn](https://twitter.com/etieno_u)
- **LinkedIn**: [Ibenge-uforo](https://www.linkedin.com/in/ibenge-uforo/)
- **Ongoing** **Research[5 min]**: [Social Survey](https://docs.google.com/forms/d/e/1FAIpQLScKBo1VQvEVpvxKbOamhWq02uQU8HlgUPq576F-LD3yTljkwg/viewform)