Skip to content

02 AutoMapper Configuration

M. Fares edited this page Mar 12, 2018 · 1 revision
  1. Install AutoMapper package using the Nuget Package Manager
  2. 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();
            });
        }
    }
}
  1. 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();
  1. 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);
  1. Read the AutoMapper documentation for advanced topics

Clone this wiki locally