adding and using in an ASP.Net Core project

When working with data (and not only), we often have to deal with the need to copy (map) the property values ​​of one object into a new object of another type.

For example, suppose that a database query returns us a record in the form of an object represented by the Person class:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
}

Next, we need to create a new object, represented by the Student class:

public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public DateTime AdmissionDate { get; set; }
}

and copy data from the properties of the object obtained from the database into its properties.

Without the help of a third party library, we would have to do it ourselves:

// получаем запись из БД
var person = _dbRepository.GetPerson(1);

// копируем значения свойств (осуществляем маппинг)
var student = new Student
{
    FirstName = person.FirstName,
    LastName = person.LastName,
    BirthDate = person.BirthDate
};

And using the AutoMapper library, mapping is done with just one line of code:

var student = _mapper.Map<Student>(person);

1. Connecting the AutoMapper library to the project and using it

Step 1

Adding packages to a NuGet project:

AutoMapper

AutoMapper.Extensions.Microsoft.DependencyInjection

To do this, in SolutionExplorer (Solution Explorer), right-click on the name of the working project and select Manage NuGet Packages… (Managing Nuget Packages).

Next, go to the leftmost tab Browse, and in the search bar enter the name of the NuGet package to be installed.

In the left window, select the package we need, and in the right, click the button Install.

We are waiting for the installation to finish.

We do these steps for both packages.

Step 2

Add the AppMappingProfile class to the project:

public class AppMappingProfile : Profile
{
		public AppMappingProfile()
		{			
			CreateMap<Person, Student>();
		}
}

In the generics of the CreateMap method, we first pass the source type of the values, and the second – the destination type.

Those. in this example, we are mapping from a Person object to a Student object.

If we want the mapping to work in both directions, we add a call to the ReverseMap() extension method:

CreateMap<Person, Student>().ReverseMap();

Now we can also map the student object to a person object:

var person = _mapper.Map<Person>(student);

Step 3

Adding AutoMapper to DI container. To do this, add the following line to the ConfigureServices method of the Startup.cs class:

public void ConfigureServices(IServiceCollection services)
{
  // другой код
  services.AddAutoMapper(typeof(AppMappingProfile));
  // другой код
}

Several mapping profile classes can be created. In this case, we pass them to the parameters of the AddAutoMapper method separated by commas:

services.AddAutoMapper(typeof(AppMappingProfile), typeof(MappingProfile2));

Step 4

We use a mapper.

Now mapping our Person object to Student happens in one line of code:

var student = _mapper.Map<Student>(person);

Below is the complete code for the class that uses the mapping:

using AutoMapper;
using AutoMapperInAspNetCore.Db;
using AutoMapperInAspNetCore.Models;

namespace AutoMapperInAspNetCore.Mapping
{
    public class MappingHelper
    {
        private readonly IMapper _mapper;
        private readonly IDbRepository _dbRepository;

        public MappingHelper(IMapper mapper, IDbRepository dbRepository)
        {
            _mapper = mapper;
            _dbRepository = dbRepository;
        }

        public void DoSomething()
        {
            // получаем запись из БД
            var person = _dbRepository.GetPerson(1);

            // Создаем новый объект типа Student и копируем в его свойства
     				// значения свойств объекта person (осуществляем маппинг)
            var student = _mapper.Map<Student>(person);
        }
    }
}

Here, as a generic, we pass the destination type (Student) to the Map method of the _mapper object, and we pass the source object (person) in the parameter.

Now we have a student object of type Student, with field values ​​from the person object.

In this case, only those fields are mapped, the names of which completely coincide for both types.

In this case, these are the fields:

public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }

2. Mapping objects with mismatched property names

For clarity, let’s slightly modify the Student class by renaming its properties:

public class Student
{
    public string Fio { get; set; }
    public DateTime Birthday { get; set; }
    public DateTime AdmissionDate { get; set; }
}

Now the names of the properties of the person and student objects do not match.

In order for the mapping to work, we will have to add explicit rules to the mapping profile:

public AppMappingProfile()
{	  
  CreateMap<Person, Student>()
    .ForMember(dest => dest.Fio, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"))
    .ForMember(dest => dest.Birthday, opt => opt.MapFrom(src => src.BirthDate));
}

where dest is the destination object and src is the source object.

In the MapFrom method for the Fio field of the student object, we have applied string interpolation −

$"{src.FirstName} {src.LastName}"

the result of which will be a string of the form “First Name Middle Name”, which will be assigned to the Fio property of the student object.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *