-
Notifications
You must be signed in to change notification settings - Fork 0
02 AutoMapper Configuration
M. Fares edited this page Mar 12, 2018
·
1 revision
- Install AutoMapper package using the Nuget Package Manager
- Create the AutoMapperConfig.cs file in App_Start folder. Copy the following code while updating the namespaces and the mappings
using SchoolWebApp.Models;
using SchoolWebApp.ViewModels;
namespace SchoolWebApp.App_Start
{
/// <summary>
/// Configuration of AutoMapper class
/// Add all the required mappings between model and view models here
/// </summary>
public static class AutoMapperConfig
{
public static void RegisterMappings()
{
AutoMapper.Mapper.Initialize(cfg =>
{
cfg.CreateMap<Employee, EmployeeViewModel>().ReverseMap();
cfg.CreateMap<Faculty, FacultyViewModel>().ReverseMap();
});
}
}
}- In the Global.asax file, add the following code at the end of the Application_Start() method
// Register AutoMapper when the app starts
AutoMapperConfig.RegisterMappings();- Use the AutoMapper in your Controllers
// Copy the properties of the employee object into the properties of model object
EmployeeViewModel model = Mapper.Map<EmployeeViewModel>(employee);- Read the AutoMapper documentation for advanced topics