What is auto-mapper and how to use it in asp.net core?.

Solution

This article is the continuation of the How to create asp.net core API’s article, So I highly encourage you to see the article understand the source code file structure of the project. This article is for how to configure Auto-Mapper for asp.net core applications. So, without you going through the below article you are probably not able to understand this article and I started using this auto mapper library to the asp.net Core Web API project. You can follow the same approach for any other like traditional Asp.net MVC, Windows, etc. Projects.

Did you ever think of object-object mapping?

When I was a beginner at the asp.net core and entity framework core concepts, and when I was started to use this framework while saving the data or fetching the data from the asp.net core entity framework. converting Database Entities or POCO object data to user View model Object data, I used a traditional foreach loop, creating a new instance of View model object to assign the data values to ViewModel Object and it was disgusting sometimes because of several loops.

To solve the issue we have one good package in our asp.net core, i.e Auto Mapper

What is Auto-mapper in asp.net core?

In simple words,  Auto-mapper helps us to copy data from one type of object to another type of object. in our case database entities results into our model object, that’s it. most of the developers like me also get bored while mapping/converting database results Entites object to custom view object entities, This type of code is rather tedious and boring to write, so why not leave that job to this Auto-Mapper?

Now, It’s time to configure Auto-mapper to our asp.net core web API Project

Step 1: Install Auto-mapper and dependency Package

Add below two packages to the project library so AutoMapper is a simple little library built to solve a deceptively complex problem – getting rid of code that mapped one object to another.

Create dto classes and POCO classes in respective folder as showed in the below images.

Step 2: Create Mapping Profile class

Profiles allows the developers to organize maps into classes, improve the code readability and maintainability. developers may create any number of profiles can be created, and added to one or more configurations as needed.

In the Below image categoryProfile.cs by inheriting the profile from auto mapper

using API_IN_COMPARE.Entities;
using API_IN_COMPARE.Models;
using AutoMapper;

namespace API_IN_COMPARE.Profiles
{
    public class CategoryProfile : Profile
    {
        public CategoryProfile()
        {

            CreateMap<Category, Categorydto>();
          //CreateMap<IEnumerable<CompareVarVal>, CompareVarValListdto>()
            //    .ForMember(q => q.CompareVarValListdtos,
            //    option => option.MapFrom(q => q.ToList()));
            //CreateMap<Company, Companydto>();
            //CreateMap<IEnumerable<Company>, CompanyListdto>()
            //    .ForMember(q => q.CompanyListdtos,
            //    option => option.MapFrom(q => q.ToList()));
            //CreateMap<CompareVarVal, CompareModeldto>()
            //.ForMember(dto => dto.CATEGORY_NAME,
            //o => o.MapFrom(a => a.Category.CATEGORY_NAME))
            //CreateMap<CompareModeldto, CompareVarVal>();
            //.ForMember(dto => dto.Category.CATEGORY_NAME, 
           //o => o.MapFrom(a => a.CATEGORY_NAME));
      }
    }
}

Step 3: register Auto mapper service servceCollection container

Register the the Mapper profiles service by using services.AddAutoMapper() in ConfigurationServices method of the startup.cs file as showed in the below image.

using API_IN_COMPARE.Data;
using API_IN_COMPARE.Interface;
using API_IN_COMPARE.SqlRepo;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;

namespace API_IN_COMPARE
{
    public class Startup
    {
        private IConfiguration _config;
        public Startup(IConfiguration configuration)
        {
            _config = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddMvc();
            services.AddDbContextPool<InCompareContext>(options =>
            {
                options.UseSqlServer(_config.GetConnectionString("EmployeeDbConnection"));
            });
            services.AddScoped<ICategory, CategoryRepository>();

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Step 5: Add the mapper dependency in contoroller

Now developer can use the mapper functionality in our class to copy the data from entity class to ViewModel or dto class without using anyc# loops.

Summary

As we discussed in above section Auto-mapper helps us to copy data from one type of object to another type of object. in our case database entities results into our model object, that’s it. most of the developers like me also get bored while mapping/converting database results Entites object to custom view object entities

Shivaraju M
Shivaraju M

Over 3+ years experience in IT industry, good knowledge in . Net-based Web applications, windows applications, web services, and SPAs. I have played
multiple roles related to technical delivery in multiple domains while working on over 10+ technologies. I am
currently focused on continuous improvement and agile project management.

Leave a Reply