First, let me introduce you to Automapper, A convention-based object-object mapper.
"AutoMapper uses a fluent configuration API to define an> object-object mapping strategy. AutoMapper uses a convention-based> matching algorithm to match up source> to destination values. Currently, AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer."domain and application layer."and application layer."
When developing Subtle (The blog engine currently used to run pieterg.com), I needed the ability to easily map the ViewModels to Domain Models. Let's say a login view for example. I will get to the GetUser method in a bit
/// <summary>
/// Account Login View Model
/// </summary>
public class AccountLoginViewModel
{
public string Username { get; set; }
public string Password { get; set; }
}
I have removed the validation attributes
/// <summary>
/// User
/// </summary>
public class User
{
public virtual int ID { get; set; }
public virtual string Username { get; set; }
public virtual string Password { get; set; }
public virtual string VerificationGuid { get; set; }
public virtual bool Verified { get; set; }
}
Now we need to tell Automapper how to map these types, and in most cases, it's generally quite good at figuring out the mapping itself.
Mapper.CreateMap<AccountLoginViewModel, User>();
This only needs to be setup once and can be done in the Global.asax. What I have chosen to do is leverage Ninject and create an AutoMapping module.Now that we have done the initial setup, let's take a look at a controller action.
[HttpPost]
public ActionResult Login(AccountLoginViewModel accountLoginViewModel)
{
//Get the user from the Account Login View Model
User user = accountLoginViewModel.GetUser();
//Validate the user
//If you have failed, pass back the accountLoginViewModel
return View(accountLoginViewModel);
}
This is our simple login action that gets passed an AccountLoginViewModel. I wanted to hide the mapping as much as possible and chose to do it in a method called GetUser(). The reason for this is so that if something goes haywire, I can pass the ViewModel back to the view and let the user correct their mistakes, also keeping the views clean and dumb.The magic of AutoMapper happens in the GetUser method
/// <summary>
/// Get User
/// </summary>
/// <returns></returns>
public User GetUser()
{
User user = new User();
AutoMapper.Mapper.Map<AccountLoginViewModel, User>(this, user);
return user;
}
There are more complex scenarios, but as a brief introduction to Automapper, I think this post will suffice.
Read More

