Setting AutoMapper to our Project
In this lesson, we're going to add AutoMapper to our project
We prepared DTOs in the last lecture. Now we need something that can map our original Entity with the DTOs. Nothing can be better than AutoMapper to do this job. We need to add this package to our API project, so let's open Nuget Package Manager and search for the package which is going to be the best for this use case. Type
AutoMapper.Extensions.Microsoft.DependencyInjection and click on that. We want to install it in the API project, so check that box and press install. Just restore the project to start using it.
Inside our API project, we can create a new folder for all the helpers we're going to use. Automapper is one of them. Let's call this folder,
Helpers, and inside, we need a class where we will map our Entities to the DTOs. let's call this file,
MappingProfiles. This class will derive from profile which will be provided by AutoMapper, so let's import it from AutoMapper. Now we need an empty constructor, so let's do that as well.
Inside here, we're going to do the mapping, so we can write CreateMap with Angled brackets. Inside, we need to mention the classes we want to map together. We have prepared our courseDto, so we can map Course to CourseDto. We have mentioned type string for our Category property, so we need to get that property from Category table — we can write
.ForMember and brackets. We want to map our category property, so we will write
c => c.Category and a comma. We want this to map from Category table with Name property, so we can write
o.MapFrom, s => s.Category.Name. What it'll do is map the properties with the same name easily. Since we want to get Category name for Category property which is a string, it will go to the Category table and get the name property for us. That's really it. Let's import Course and CourseDto to get rid of the error.
We also need to map the Learning to LearningDto and Requirement to RequirementDto, so let's write CreateMap and inside angled brackets, we can map Learning to LearningDto. Now let's copy it and replace learning with requirement.
public class MappingProfiles : Profile
.ForMember(c => c.Category, o => o.MapFrom(s => s.Category.Name));
Now we will go to the startup class and add AutoMapper as a service. Order doesn't matter here so I can write services.AddAutoMapper and then we will mention the assembly of it . We will write type of which will be MappingProfiles class that we have just created. Let's import AddAutoMapper from AutoMapper and MappingProfiles from Helpers. This is really it, we can now start using them in our controllers. Let's go to the CoursesController.