AutoMapper in ASP.NET Core MVC


AutoMapper maps the object to the object. It maps the value of one object to another. In MVC, often you need to map the value of one object to another. For example, after getting the result from a table, the value must be transferred to another view model object. Only then you can pass the view model to View, to display the value. So Automapper makes your work easier.

Automapper is open source, so you can get it with the nuget package manager. The following is a command to install the AutoMapper in your application. 

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

After installation, you can view the AutoMapper under packages.


In order for the AutoMapper to work, you first need to add it to the ConfigureServices method in Startup.cs

using AutoMapper;
public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper(typeof(Startup));
    services.AddControllersWithViews();
}

Let’s first create a student class to map the objects
 
public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Grade { get; set; }
}

This class is a StudentViewModel class that is going to get value from the student class.
 
public class StudentViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

The StudentViewModel class has only three property values. But there are five values in the Student class.When we map the value from the Student object, it will map the appropriate property values.


Sometimes the destination object may have additional values. 

For example, imagine the StudentViewModel has Course property, In that case the Course property value will be null when mapping.


The following is a mapping profile code. Here the mapping profile is created using CreateMap for Student and StudentViewModel 

AutoMapping.cs
using AutoMapper;
public class AutoMapping : Profile
{
    public AutoMapping()
    {
        CreateMap<Student, StudentViewModel>();
    }
}

The following is a home controller code. Here the IMapper interface is injected into the HomeController constructor. In the Index action method, values are assigned to Student class. Next the using _mapper.map function stud object values are mapped to the studModel.

public class HomeController : Controller
{
    private readonly IMapper _mapper;

    public HomeController(IMapper mapper)
    {
        _mapper = mapper;
    }

    public IActionResult Index()
    {
        Student stud = new Student() { 
        Id =1,
        FirstName = "Peter",
        LastName = "Parker",
        Age = 15,
        Grade = "Tenth grade"
    };

    StudentViewModel studModel = _mapper.Map<Student, StudentViewModel>(stud);

    return View(studModel);
}

The following is a view code to display the result in webpage
@model StudentViewModel

<h4>AutoMapper Demo</h4>
    <table>
        <tr>
            <td>First Name:</td>
            <td> <b>@Model.FirstName</b> </td>
        </tr>
        <tr>
            <td> Last Name: </td>
            <td> <b>@Model.LastName</b> </td>
        </tr>
        <tr>
            <td>Age:</td>
            <td><b>@Model.Age</b> </td>
        </tr>
    </table>

The following is a screenshot of the above code. Here you can see how the values are mapped to the Student object to StudentViewModel object. 


We can’t always expect the source object property name and the destination property name should be the same. 

Sometimes it differs, considering the following StudentViewModel here the first name spelling is FrstNm and last name spelling is LstNm. 
 
public class StudentViewModel
{
    public string FrstNm { get; set; }
    public string LstNm { get; set; }
    public int Age { get; set; }
    public string  Course { get; set; }
}

To map this different property value, you need to map the property using the ForMember method in the profile. 

 public class AutoMapping : Profile
    {
        public AutoMapping()
        {
            CreateMap<Student, StudentViewModel>()
                .ForMember(x=>x.FrstNm, 
                opt => opt.MapFrom(src=>src.FirstName))
                .ForMember(x => x.LstNm,
                opt => opt.MapFrom(src => src.LastName));
        }
    }

I hope this article will help you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Creating a C# Azure Function with Visual Studio: Step-by-Step Guide

Exploring EventCallback in Blazor: Building Interactive Components