综合编程

How To Implement AutoMapper In ASP.NET Core MVC Application

微信扫一扫,分享到朋友圈

How To Implement AutoMapper In ASP.NET Core MVC Application
0 0

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
感谢您的支持!

    1分钟知识锦囊 | 为什么这两年突然冒出来这么多耳机品牌?

    上一篇

    OG iPhone prototype up for auction on eBay

    下一篇

    您也可能喜欢

    评论已经被关闭。

    插入图片