How To Implement AutoMapper In ASP.NET Core MVC Application

综合编程 2018-08-30 阅读原文

In this demo, I will show how to utilize the Automapper library efficiently. Automapper makes our lives easy with minimal steps. In a nutshell, AutoMapper is an object-object mapper. It transforms the input object of one type into an output object of another type.

Requirements

  • Visual Studio 2017.
  • Auto Mapper NuGet Package
  • Auto Mapper Dependency Injection Package

In this example, I’ve taken two classes, Employee and EmployeeModel.

namespace ASPNETCORE_AUTOMAPPER.Models {  
    public class Employee {  
        public int Id {  
            get;  
            set;  
        }  
        public string Name {  
            get;  
            set;  
        }  
        public string Designation {  
            get;  
            set;  
        }  
        public string City {  
            get;  
            set;  
        }  
        public string State {  
            get;  
            set;  
        }  
    }  
}  
namespace ASPNETCORE_AUTOMAPPER.Models {  
    public class EmployeeModel {  
        public int Id {  
            get;  
            set;  
        }  
        public string Name {  
            get;  
            set;  
        }  
        public string Designation {  
            get;  
            set;  
        }  
        public Address Address {  
            get;  
            set;  
        }  
    }  
    public class Address {  
        public string City {  
            get;  
            set;  
        }  
        public string State {  
            get;  
            set;  
        }  
    }  
}  

We are getting Employee object from the end user and trying to assign it to EmployeeModel with each property like below, which is a tedious job and in real time scenarios, we may have plenty of properties as well as complex types. So this is an actual problem.

[HttpPost]  
public EmployeeModel Post([FromBody] Employee employee) {  
    EmployeeModel empmodel = new EmployeeModel();  
    empmodel.Id = employee.Id;  
    empmodel.Name = employee.Name;  
    empmodel.Designation = employee.Designation;  
    empmodel.Address = new Address() {  
        City = employee.City, State = employee.State  
    };  
    return empmodel;  
}  

To overcome this situation, we have a library called AutoMapper.

Incorporate this library into your application by following the below steps.

Open Visual Studio and Click on File - New Project and select ASP.NET CORE WEB APPLICATION,

Click on Ok and you’ll get the below window where you have to select WebApp (MVC).

As soon as you click on the Ok button your application is ready.

Now, the actual auto mapper should take place. For that, we need to add NuGet reference to the solution. Make sure we have to add two references to solution

  • Add Main AutoMapper Package to the solution,

  • Now, add the Auto mapper dependency Injection Package,

  • Now, call AddAutoMapper from StartUp.cs file as shown below,
    public void ConfigureServices(IServiceCollection services) {  
        services.AddMvc();  
        services.AddAutoMapper();  
    }  
    
  • Now, create the MappingProfile.cs file under the root project and write the below snippet
    public class MappingProfile: Profile {  
        public MappingProfile() {  
            CreateMap  ()  
        }  
    }  
    
  • Here CreateMap method is used to map data between Employee and EmployeeModel.

If you observe here we called ForMember method, which is used when we have different datatypes in source and destination classes.

Employee Class should be like this,

namespace ASPNETCORE_AUTOMAPPER.Models {  
    public class Employee {  
        public int Id {  
            get;  
            set;  
        }  
        public string Name {  
            get;  
            set;  
        }  
        public string Designation {  
            get;  
            set;  
        }  
        public string City {  
            get;  
            set;  
        }  
        public string State {  
            get;  
            set;  
        }  
    }  
}  

EmployeeModel.cs should be like this,

namespace ASPNETCORE_AUTOMAPPER.Models {  
    public class EmployeeModel {  
        public int Id {  
            get;  
            set;  
        }  
        public string Name {  
            get;  
            set;  
        }  
        public string Designation {  
            get;  
            set;  
        }  
        public Address Address {  
            get;  
            set;  
        }  
    }  
    public class Address {  
        public string City {  
            get;  
            set;  
        }  
        public string State {  
            get;  
            set;  
        }  
    }  
}  

In Employee.cs file having City and State properties but in EmployeeModel.cs we have Address type. So if we try to map these two models we may end up missing type configuration error. So to overcome that issue we have to use ForMember method which tells mapper what properties it should map for that particular Address field. So we have to tweak the MappingProfile.cs file like below:

public class MappingProfile: Profile {  
    public MappingProfile() {  
        CreateMap  ().ForMember(dest => dest.Address, opts => opts.MapFrom(src => new Address {  
            City = src.City, State = src.State  
        }));  
    }  
}  

So the next step is we have to hook this up from our controller; just follow the below snippet

namespace ASPNETCORE_AUTOMAPPER.Controllers {  
    public class EmployeeController: Controller {  
        private readonly IMapper _mapper;  
        public EmployeeController(IMapper mapper) {  
            _mapper = mapper;  
        }  
        public IActionResult Index() {  
                return View();  
            }  
            [HttpPost]  
        public EmployeeModel Post([FromBody] Employee employee) {  
            EmployeeModel empmodel = new EmployeeModel();  
            empmodel = _mapper.Map  (employee);  
            return empmodel;  
        }  
    }  
}  

Here we have injected IMapper to EmployeeController and performed mapping operation between Employee and EmployeeModel

If you pass data to Employee object, it will directly map to EmployeeModel object with the help of Mapper.

Now if you observe, EmployeeModel is filled in with all the property data with the help of Mapper. This is the actual beauty of AutoMapper.

So if you come across a requirement to map data from your DTOs to Domain object choose Automapper and it will do all your work with less code.

C-Sharpcorner

责编内容by:C-Sharpcorner阅读原文】。感谢您的支持!

您可能感兴趣的

用VSCode开发一个基于asp.net core 2.0/sql server linux(doc... 第一部分: http://www.cnblogs.com/cgzl/p/8478993.html 第二部分: http://www.cnblogs.com/cgzl/p/8481825.html 由于本文主要是讲VSCode...
现代程序框架模式,MV-X mv-x的含义 M:Model V:View X:View和Model的桥梁 MVC C:Controller 大致定义: View和Model一般没有交集,它们的交流通过Controller来进行,即: M...
在Asp.Net Core中使用DI的方式使用Hangfire构建后台执行脚本... 最近项目中需要用到后台Job,原有在Windows中我们会使用命令行程序结合计划任务或者直接生成Windows Service,现在.Net Core跨平台了,虽然Linux下也有计划任务,但跟原有方式一样,没撒图形界面,执行结果之类...
MVC pattern from scratch Before starting, the reader considers this my personal opinion, how I see the things and not the only way for implement ...
SimpleMembershipProvider: web&lowbar... which is the best method to access to webpages_Membership table informations using a SimpleMembershipProvider in MVC 4? ...