Monday 7 January 2013

Using Automapper with ASP.NET MVC application

Automapper is a convention based object - object mapper.  It is available in GitHub.  Here I explain about how to use Automapper to map between domain model objects and view model objects in ASP.NET MVC applications.  Install Automapper to the project through Nuget.  
Let us take a simple example of Employee model as follows : 
public class Employee
    {
        public int EmployeeId { get; set; }
        
        public string EmployeeName { get; set; }
    }
And my Employee view model as follows :
public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }
        
        public string EmployeeName { get; set; }

    }
 Consider there is a strongly typed view which expects a model object of type EmployeeViewModel.  So after querying with the Emplyee model object, we need to map this to EmployeeViewModel object.
Here is the use of AutoMapper.
AutoMapper can be configured in the web project.  To make this more maintainable, create a folder (say Mappings) in the solution.
Here we can create two profile classes.  One for mapping from domain model object to view model object and another one for reverse mapping.
public class DomainToViewModelMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "DomainToViewModelMappings"; }
        }

        protected override void Configure()
        {
            Mapper.CreateMap<Employee, EmployeeViewModel>();
        }
    }

public class ViewModelToDomainMappingProfile : Profile
    {
        public override string ProfileName
        {
            get { return "ViewModelToDomainMappings"; }
        }

        protected override void Configure()
        {
            Mapper.CreateMap<EmployeeViewModel, Employee>();
        }
    }
Now create a configuration class inside Mappings folder.
public class AutoMapperConfiguration
    {
        public static void Configure()
        {
            Mapper.Initialize(x =>
            {
                x.AddProfile<DomainToViewModelMappingProfile>();
                x.AddProfile<ViewModelToDomainMappingProfile>();
            });
        }
    }
And then call this configuration from Global.asax.
AutoMapperConfiguration.Configure();
And from the controller easily map the employeeObject (domain model object) to employeeViewModelObject (view model object) and vice versa.
var employeeViewModelObject = Mapper.Map<Employee, EmployeeViewModel>(employeeObject);
In advanced scenario we can even customize the configuration.  For example we can map a particular property from source to destination. 
Mapper.CreateMap<X, XViewModel>()
                .ForMember(x => x.Property1, opt => opt.MapFrom(source => source.PropertyXYZ));
Automapper gives really a better and easy way to map between objects.