Keep your code clean with AutoMapper

Explaining How to use AutoMaptter with ASP.NET Core web App

Yohan Malshika
5 min readAug 30, 2020
Keep your code clean with AutoMapper

Hi All! Hope you all are doing well. If you are working with Asp.NET, I think you already know about AutoMapper. But when I start my internship in 99X, actually I hadn’t idea about AutoMapper and sometimes I was confused about existing code without knowing about AutoMapper. So today I’ll share some experiences with you guys.

1. What is AutoMapper?

AutoMapper is a component that helps to copy data from one type of object to another type of object. It is more like an object-object mapper. Basically, AutoMapper helps us to transform one object type to another.

2. Why do we need AutoMapper?

Yeah, When we building the application we have kept the separation between our domain models and our view models. So for that, we have to write the code that allows us to map our domain model into our view model.

Student.cs class

public class Student
{
public string StuId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}

StudentDTO.cs class

public class StudentDTO
{
public string StuId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}

Now we have to map these objects. Then we create a method that can take input from the StudentDTO and then map the values into the Student class object(view model).

public Student MapObjects(StudentDTO stud)
{
return new Student(){
stuId = stud.stuID,
name = stud.FullName,
age = stud.Age,
city = stud.City,
};
}

You can see the traditional way that we used to map objects. But this is totally okay with this type of object. But think when our class has so many properties, we have to map those properties one by one. Then it will be difficult and it also reduces the code readability and cleanliness. So there is a simple solution we can use to solve this problem and it is AutoMapper. So basically that’s why we use AutoMapper.

3. How to use AutoMapper in our ASP.NET Core Application

Let’s see how to use AutoMapper with our ASP.NET Core Application.

First, create a ASP.NET Core project with a Web API template, and then we have to install the package into our project.

Package Name — AutoMapper.Extensions.Microsoft.DependencyInjection

Then we have to configure the service in Startup.cs class.

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
}

That’s it for the configuration part. When we do configuration, best practice is to use the extension method instead of configuring our services in ConfigureServices method in the startup.cs class. Already I mentioned it in my previous blog article. But now we have to configure one service, So it’s totally okay for now.

Let’s create a two classed called StudentDTO.cs and Student.cs

Student.cs

public class Student
{
public string StuId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}

StudentDTO.cs

public class StudentDTO
{
public string StuId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}

Then create a folder called Helper and then create AutoMapProfile.cs class for which inherit the Profile class of AutoMapper and then have to use CreateMap<source, destination>() to create a mapping between classes.

public class AutoMapProfile : Profile
{
public AutoMapProfile()
{
CreateMap<StudentDTO, Student>();
}
}

Now we mapped our classes and when the application starts it will initialize AutoMapper and then AutoMapper scan all assemblies and classes that we inherit from the AutoMapper Profile class. Then load mapping configurations.

4. Map two objects with IMapper

IMapper interface is used to map two objects. So for that, we have to create a new controller called StudentController.cs.

[Route("api/[controller]")]
[ApiController]
public class StudentController : ControllerBase
{
private readonly IMapper _mapper;public StudentController(IMapper mapper)
{
_mapper = mapper;
}
[HttpGet]
public Student Get()
{
StudentDTO studentDTO = new StudentDTO(){
StuId = "STU001"
Name = "Yohan",
Age = 25,
City = "Kalutara",
};
return _mapper.Map<Student>(studentDTO);
}
}

Now you can see we created a new object of StudentDTO class and assign values to it inside Get() method. Then we map our StudentDTO object with the Student class. So for that, we use _mapper.Map() method.

5. Few cool features of AutoMapper

Projection

I know, now you have a problem. What happens when the source class has a different property name than the destination class. Let’s see how to solve this problem.

Student.cs

public class Student
{
public string StuId { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
public string City { get; set; }
}

StudentDTO.cs

public class StudentDTO
{
public string StuId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}

Now you can see, there is a different between StudentDTO and Student classes. It is Name and FullName properties names are not matching.

To solve this problem, AutoMapper has a feature called Projection.

Let’s see it.

public class AutoMapProfile : Profile
{
public AutoMapProfile()
{
CreateMap<StudentDTO, Student>().
ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name));
}
}

So to solve this problem we have to define a mapping to all the property which are different it both classes. You can see it in the above code example.

Conditional Mappings with AutoMapper

We know we have used some conditions when we map properties. And the good thing is Automapper has a feature for it. So while writing mappings we can set conditions for each property.

public class AutoMapProfile : Profile
{
public AutoMapProfile()
{
CreateMap<StudentDTO, Student>()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.isTeen, opt => opt.MapFrom(src => src.Age < 18 ? true : false));
}
}

You can see the above example. isAdult property is calculated based on the condition that Age must be greater than 18.

So there is a lot of features we can use with AutoMapper. Some of them are Nested Mapping, Reverse Mapping and etc. So still if you are not using AutoMapper, try it in your code. it will keep our code and clean and also increase the readability of our code.

So That’s it for today. I think you learned something new from my article.

See you again soon with another article !!

Learn More

--

--