AutoMapper in Asp.net Core 7 Web API
Tags: webdev, beginners, programming, html
Published: 2023-03-31 18:58:49

## Introduction:
A straightforward package called AutoMapper enables us to convert one object type into another. It is a convention-based object-to-object mapper with minimal configuration requirements.
## When we use Auto Mapper 
When developing apps, it's common to wish to map items to either comparable or different kinds. Why do you frequently require this? The database tables of the employed database are typically mapped with the models (also known as entities) in an application. 
As a result, there is frequently a discrepancy between the model class properties and the data transfer object class properties. You may run into issues because of having to write a lot of boilerplate code to convert instances of disparate types. A large application, like an ERP, could require a lot of models and data transfer object classes. Writing code to perform the mapping manually would be time-consuming. Here, programs like AutoMapper can be useful.

### Step No 1
Install the NuGet package from NuGet Package Library.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3z0vf2zyi58w6otg8p67.png)

- AutoMapper

- 
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

### Step No 2 
Configure the automapping in the Program.cs Class 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jeom5hxiyh7zh9m514vz.png)

```
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAutoMapper(typeof(Program));

```
### Step No 3
Let’s Create the Model and Data Transfer Object.

```
public class Event :BaseEntity
    {
        public string EventType { get; set; }
        public string EventPriority { get; set; }
        [MaxLength(50)]
        public string EventName { get; set; }
        public string EventStatus { get; set; }
        [Required]
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        [MaxLength(50)]
        public string EstimatedDuration { get; set; }
        [MaxLength(200)]
        public string Description { get; set; }
        [MaxLength(200)]
        public DateTime? LastStatusChangeDate { get; set; }
        public long? JobId { get; set; }


    }

```

```
Let’s create the Data Transfer Object.
public class DTOEvents
    {
        public string EventType { get; set; }
        public string EventPriority { get; set; }
        [MaxLength(50)]
        public string EventName { get; set; }
        public string EventStatus { get; set; }
        [Required]
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        [MaxLength(50)]
        public string EstimatedDuration { get; set; }
        [MaxLength(200)]
        public string Description { get; set; }
        [MaxLength(200)]
        public string Tags { get; set; }
        public DateTime? LastStatusChangeDate { get; set; }
        public long? JobId { get; set; }

    }

```
### Step No 4 
Now Add the Profile for these two Objects 

```
public class AutoMapper: Profile
    {
        public AutoMapper()
        {
            CreateMap<Event, DTOEvents>();
        }
    }

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d9q6vuq140fesvlh98l1.png)

### Step No 5
Now we will add auto mapper in our Controller. First, we will inject the mapper into Controller Constructor after that we will map the event model with EventDTO.

```
using Ac.Jobs.API.DTos;
using AC_Jobs_API_Domian_Layer.Data;
using AC_Jobs_API_Domian_Layer.Models;
using AC_Jobs_API_Service_Layer.IService;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace AC_Jobs_API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class EventsController : ControllerBase
    {
        private readonly ICustomService<Event> _customService;
        private readonly ApplicationDbContext _applicationDbContext;
        private readonly IMapper _mapper;

        public EventsController(ICustomService<Event> customService, ApplicationDbContext applicationDbContext, IMapper mapper)
        {
            _customService = customService;
            _applicationDbContext = applicationDbContext;
            _mapper = mapper;
        }
        [HttpGet(nameof(GetEventById))]
        public IActionResult GetEventById(int Id)
        {
            var obj = _customService.Get(Id);
            if (obj == null)
            {
                return NotFound();
            }
            else
            {
                return Ok(obj);
            }
        }
        [HttpGet(nameof(GetAllEvent))]
        public IActionResult GetAllEvent()
        {
            var obj = _customService.GetAll();
            if (obj == null)
            {
                return NotFound();
            }
            else
            {
                return Ok(obj);
            }
        }
        [HttpPost(nameof(CreateEvent))]
        public IActionResult CreateEvent(DTOEvents events)
        {

            try
            {
                if (events != null)
                {
                    var eventsdata= _mapper.Map<Event>(events);
                    _customService.Insert(eventsdata);
                    return Ok("Created Successfully");
                }
                else
                {
                    return BadRequest("Somethingwent wrong");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        [HttpPost(nameof(UpdateEvent))]
        public IActionResult UpdateEvent(DTOEvents events)
        {
            if (events != null)
            {
                var eventsdata = _mapper.Map<Event>(events);
                _customService.Update(eventsdata);
                return Ok("Updated SuccessFully");
            }
            else
            {
                return BadRequest();
            }
        }
        [HttpDelete(nameof(DeleteEvent))]
        public IActionResult DeleteEvent(DTOEvents events)
        {
            if (events != null)
            {
                var eventsdata = _mapper.Map<Event>(events);
                _customService.Delete(eventsdata);
                return Ok("Deleted Successfully");
            }
            else
            {
                return BadRequest("Something went wrong");
            }
        }
    }
}

```
## Conclusion
With the help of AutoMapper, you can map your business objects to data transfer objects without having to write boilerplate code, which clears up the code in your application's source code. When your application requires a complicated mapping of incompatible types, you should utilize AutoMapper.