Add AutoMapper to .Net 6

In this article we will be adding AutoMapper to our AspNetCore 6 application.

You can watch the full video on Youtube

The first thing we need to do is add the packages

dotnet add package AutoMapper –version 10.1.1
dotnet add package AutoMapp…


This content originally appeared on DEV Community and was authored by Mohamad Lawand

In this article we will be adding AutoMapper to our AspNetCore 6 application.

You can watch the full video on Youtube

The first thing we need to do is add the packages

dotnet add package AutoMapper --version 10.1.1
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection --version 8.1.1

The next step is adding the AutoMapper to our DI container, inside the program.cs we need to add the following

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

Now its time to create our AutoMapper profiles, so on the root directory of our application we need to create a folder called Profiles, inside the Profiles folder we will create a new class called UserProfile ("We can call the class anything we want, but per convention we need to name the class based on the entity we want to map as well add the word profile to it").

We are going to map the below entity ("User") to the a Dto ("UserDto")

public class User
    {
        public Guid Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string Country { get; set; }
        public string Address { get; set; }
        public string MobileNumber { get; set; }
        public string Sex { get; set; }
    }
public class UserDto
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string DateOfBirth { get; set; }
        public string Country { get; set; }
    }
}

Now inside the UserProfile class we need to add the following

public class UserProfile : Profile
    {
        public UserProfile()
        {
            CreateMap<UserDto, User>()
                .ForMember(
                    dest => dest.FirstName,
                    opt => opt.MapFrom(src => $"{src.FirstName}")
                )
                .ForMember(
                    dest => dest.LastName,
                    opt => opt.MapFrom(src => $"{src.LastName}")
                )
                .ForMember(
                    dest => dest.Email,
                    opt => opt.MapFrom(src => $"{src.Email}")
                )
                .ForMember(
                    dest => Convert.ToDateTime(dest.DateOfBirth),
                    opt => opt.MapFrom(src => $"{src.DateOfBirth}")
                )
                .ForMember(
                    dest => dest.Phone,
                    opt => opt.MapFrom(src => $"{src.Phone}")
                )
                .ForMember(
                    dest => dest.Country,
                    opt => opt.MapFrom(src => $"{src.Country}")
                )
                .ForMember(
                    dest => dest.Status,
                    opt => opt.MapFrom(src => 1)
                );
        }
    }

The UserProfile class MUST inherit from Profile class in order for AutoMapper to recognise it.

Inside the constructor we define the mapping between the Entity and the Dto.

Once we complete our profile mapping its now to utilise our new map in our controller.

public class UsersController : ControllerBase
{
    public IUnitOfWork _unitOfWork;
    // define the mapper
    public readonly IMapper _mapper;

    // initialise the dependencies with constructor initialisation
    public UsersController(
        IMapper mapper,
        IUnitOfWork unitOfWork)
    {   
        _mapper = mapper;
        _unitOfWork = unitOfWork;
    }

    [HttpPost]
    public async Task<IActionResult> AddUser(UserDto user)
    {
        // utilise the mapping :)
        var _mappedUser = _mapper.Map<User>(user);

        await _unitOfWork.Users.Add(_mappedUser);
        await _unitOfWork.CompleteAsync();

        var result = new Result<UserDto>();
        result.Content = user;

        return CreatedAtRoute("GetUser", new { id = _mappedUser.Id}, result); // return a 201
    }
}

So basically we need to initialise the mapper with constructor initialisation.

Then we need to utilise as follow

        var _mappedUser = _mapper.Map<Entity>(dto);

AutoMapper is a powerful tool to keep in our toolset while developing any .Net applications.


This content originally appeared on DEV Community and was authored by Mohamad Lawand


Print Share Comment Cite Upload Translate Updates
APA

Mohamad Lawand | Sciencx (2021-12-10T08:24:12+00:00) Add AutoMapper to .Net 6. Retrieved from https://www.scien.cx/2021/12/10/add-automapper-to-net-6/

MLA
" » Add AutoMapper to .Net 6." Mohamad Lawand | Sciencx - Friday December 10, 2021, https://www.scien.cx/2021/12/10/add-automapper-to-net-6/
HARVARD
Mohamad Lawand | Sciencx Friday December 10, 2021 » Add AutoMapper to .Net 6., viewed ,<https://www.scien.cx/2021/12/10/add-automapper-to-net-6/>
VANCOUVER
Mohamad Lawand | Sciencx - » Add AutoMapper to .Net 6. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/12/10/add-automapper-to-net-6/
CHICAGO
" » Add AutoMapper to .Net 6." Mohamad Lawand | Sciencx - Accessed . https://www.scien.cx/2021/12/10/add-automapper-to-net-6/
IEEE
" » Add AutoMapper to .Net 6." Mohamad Lawand | Sciencx [Online]. Available: https://www.scien.cx/2021/12/10/add-automapper-to-net-6/. [Accessed: ]
rf:citation
» Add AutoMapper to .Net 6 | Mohamad Lawand | Sciencx | https://www.scien.cx/2021/12/10/add-automapper-to-net-6/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.