Save time with AutoMapper

Recently did a load of view model classes which were basically flattened or otherwise simplified versions of an underlying DAL project which served up EntitySet objects – with all the heavy change tracking logic and navigation properties that involves.

Half ways through this, RSI was setting in, and I was getting really (really) bored of writing code like this.CustomerId = customer.CustomerId; – and when you get bored, you start making mistakes – and… well it was starting to look like a very long afternoon, let’s leave it at that.

So – I remembered someone once talking about AutoMapper being an excellent free tool for managing this kind of logic. So headed over to http://automapper.codeplex.com/ and downloaded the project – and after some very simple configuration steps I was able to map entire objects in one line of code.
AutoMapper at the most basic “out of the box” level will simply map properties on their name.
For me it worked really well to AutoMap most of the properties -and for anything more advanced, I would simply name the target property differently and do whatever custom mapping logic was required manually.
If you don’t have this level of flexibility – or if you just want to get more involved there is a vast amount of configuration options for you to look into.

Quick overview of steps to setup in an ASP.NET (MVC) application:

Add a static method to configure AutoMapper:

	public class InitAutoMapper
	{
		public static void Configure()
		{
			Mapper.CreateMap<Category, CategoryModel>();
			Mapper.CreateMap<CategoryModel, Category>(); //Two way binding
			....etc

Configure AutoMapper on application start (Global.asax):

	protected void Application_Start(object sender, EventArgs e)
	{
		InitAutoMapper.Configure();
	}

Start using – in this example an overloaded constructor is doing the mapping:

	public class CategoryModel
	{
		public CategoryModel(Category category)
		{
			AutoMapper.Mapper.Map(category, this); //(source, destination) - will map all properties where names match
		}
	}
Advertisements

One Response to Save time with AutoMapper

  1. nathan says:

    Reblogged this on Nathan.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: