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.

7 comments:

  1. And what's the gain with the profile? You could also create the inverse mapping without a profile.

    ReplyDelete
    Replies
    1. Hi Alfredo,

      You're right that the inverse mapping can be done without the Profile class. This example uses the ProfileName property to demonstrate the mapping has occurred. You could display employeeViewModel.ProfileName in the page to check if ProfileName equals "DomainToViewModelMappings".

      That was a good question, it made me think!

      Delete
  2. I would say using the profile gives you a cleaner way to create and manage and maintain your mappings in a single place.

    Thank you for this, very helpful!

    ReplyDelete
  3. Good one but I think there should be a little more code with explanation, then it would have been more useful for the beginners as well.

    Thanks...Keep up the good work

    ReplyDelete
  4. I was having a hard time trying to figure out how to configure AutoMapper (Newbie) until I came across this tutorial. Thanks mate

    ReplyDelete
  5. Hire php developers – Save cost by hiring dedicated PHP developers & PHP programmer from this site.

    ReplyDelete