Hello readers. It’s been a while because Aqua Bird Consulting has been doing some awesome work recently and I am finding it hard to sit down and write. But today I found some time, so you will get an experimental post about Asp.Net MVC and Automapper.

This post is targeted toward those developers who use a ViewModel to as the foundation to their views. When using the ViewModel pattern there is always the pain of mapping. Mapping is central to any ViewModel pattern. You have your domain model that maps to your ViewModel, which is representative of your view. Before you continue reading I am assuming you are familiar with the basics of Asp.Net MVC.

As of right now, Asp.Net MVC has no mapping library built in. This means you have two options: Map the objects yourself manually inside the controller action, or delegate it to a third party library like AutoMapper. I usually choose the later due to it’s ease and readability in code.

Let’s looks at the final product and I’ll explain what is happening from a high level. Below you will see two methods, one for a GET and one for a POST to show that I can map out to the view and in from a request.

    public class HomeController : MappingController
    {
        public ActionResult Index()
        {
            var person = new Person
                            {
                                Name = "Khalid Abuhakmeh",
                                Address = new Address {City = "Camp Hill", Street = "111 November Dr"}
                            };

            return ViewModel<indexviewmodel>(person);
        }

        [HttpPost]
        public ActionResult Index( [IndexViewModelMap] Person person)
        {
            return ViewModel<indexviewmodel>(person);
        }
    }

You will notice two subtle differences about the code above. First of all, at the end of each action you notice that I call ViewModel<IndexViewModel>(person) instead of View(person). Secondly, in the second action I have an attribute of IndexViewModelMap.

The ViewModel method takes your domain model and maps it to the ViewModel you specify. All you have to do is specify AutoMapper map somewhere else in your code. What is the advantage of doing this? Well for one, your controllers have reduced noise, no more mapping things right in your controller action. Secondly, you still get to work with your domain objects and not have to worry about the ViewModels except for view purposes.

The IndexViewModelMap just tells Asp.Net MVC to use a ModelBinder designed to use AutoMapper. It takes the incoming IndexViewModel and maps it to the Person model. Now you can deal with your person object directly without knowing of your ViewModel.

What if my ViewModel has more than one domain model mapped to it?

Well I’ve thought of that. Rarely does a ViewModel simply map to one object. If I couldn’t handle that then there would be no point to this post. Check this out.

   public ActionResult Complex()
        {
            var person = new Person
            {
                Name = "Khalid Abuhakmeh",
                Address = new Address { City = "Camp Hill", Street = "111 November Dr" }
            };

            var car = new Car()
                          {
                              Color = "Black",
                              Make = "Audi",
                              Model = "A4"
                          };

            return ViewModel(person,car);
        }

Now I am mapping two to infinity objects to your ViewModel. That is where the money is at, if I do say so myself. To get this working all you need is to define your AutoMapper Maps and you are ready to go. Let me show you what a Mapping class looks like.

        public static void Person_To_ComplexViewModel()
        {
            AutoMapper.Mapper.CreateMap()
                .ForMember(target => target.Name, opt => opt.MapFrom(source => source.Name))
                .ForMember(target => target.City, opt => opt.MapFrom(source => source.Address.City))
                .ForMember(target => target.Street, opt => opt.MapFrom(source => source.Address.Street));
        }

That is easy right!

To see all of this code check it out at GitHub http://github.com/khalidabuhakmeh/AutoMapperExperiment.

Let me know what you think.