Use AutoMapper to Map ViewModels to Entities – MVC3 and Razor


Posted on : 23-09-2011 | By : Chris | In : MVC

Quite often it is prudent to create ViewModel classes to encapsulate multiple pieces of data (represented by instances of classes) into one easy to manage object that you can pass to your View. This is all well and good but additions and deletes must then  map the data back to the corresponding entities.

  • Mapping code is tedious to write
  • Mapping code is tedious to test

In fact, some of the most boring code in the world to write is mapping between two objects. Enter AutoMapper, described as:

…an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper’s established convention, almost zero configuration is needed to map two types.


Here’s an uber simple example of it in use:



namespace BenefitsBenchmarkingTool.ViewModels
    public partial class CompanyDepartments
        public int CompanyID { get; set; }
        public IEnumerable<SelectListItem> Companies { get; set; }
        public string DepartmentName { get; set; }
        public string DepartmentEmail { get; set; }


The View then references the ViewModel: @model BenefitsBenchmarkingTool.ViewModels.CompanyDepartments



public ActionResult Create(CompanyDepartments departmentToCreate)
    if (ModelState.IsValid)
        AutoMapper.Mapper.CreateMap<CompanyDepartments, Department>();
        Department newDepartment = new Department();
        AutoMapper.Mapper.Map(departmentToCreate, newDepartment);
    return RedirectToAction("Index", new { id = departmentToCreate.CompanyID });

For more information, check out this excellent post:

Post a comment