Section 7: Auto Mapper
Introduction:
In the previous sections, we have created a Hotel Model and added it to the Database, and also, we have created a Repository pattern to facilitate Database operations. We have also seen how Data Transfer Objects (DTOs) are important to minimize vulnerabilities.
When using DTOs, we may need to frequently map(convert) the Model to its DTOs and vice-versa. We can do it manually or use Auto Mapper. Hence, Auto Mapper is an object-to-object mapper where we can map one object to another.
If you have not seen my previous Sections, Auto Mapper is a object-to-object mapper where we can map one object to an another. If you have a class, say Class_1, with properties a,b,c,d, and e. And you have another class, say Class_2, with properties a,c,d, then you can map between Class_1 and Class_2 using Auto Mapper. Still confused? I would recommend you to check my previous Sections.
Implementation:
To implement Auto mapper, we need to add Auto Mapper NuGet Packages. In your solution, Navigate to NuGet package manager, and search for Auto Mapper and install the below packages.
Next, we need to create a mapping class. This class will instruct the Auto Mapper on how to map the properties of one class to another.
This mapper class is derived from the Profile class, which is defined in the AutoMapper package.
public class AutoMapper: Profile
{
public AutoMapper()
{
CreateMap<Hotel, HotelDTO>().ReverseMap();
}
}
Here we have created a constructor, and added the line:
CreateMap<Hotel, HotelDTO>().ReverseMap();
This tells the AutoMapper that it has to map between Hotel and HotelDTO objects, and ReverseMap says that it has to map Hotel to HotelDTO and vice-versa.
Next, we need to register the Automapper with our service. As a common way of registering any class with our service, we need to add the below code in ConfigureServices(IServiceCollection services)
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<HotelDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddAutoMapper(typeof(MyAutoMapper));
services.AddControllers();
}
Outroduction:
This section has learned how to copy(map) our Model object to the DTO object. Automapper works on naming conventions, i.e., it will expect the property names of both the objects to be the same. However, if it is not the same, AutoMapper still provides a way to map the objects. But, I am not covering that in this section.
In the next section, let us see how to create a Controller.