Complex Object Mapping Using AutoMapper

AutoMapper is an awesome open source library that allows automatic object-to-object mapping.  There are various getting-started blog posts and articles on the web (e.g. Getting Started Guide and AutoMapper on CodeProject) that will get you started with AutoMapper.  I was recently challenged with a particular situation using AutoMapper that wasn’t immediately clear and took me a little investigating and some trial and error work, so I will share that with you.

My source object exposed some simple properties as well as a generic List property of another type.  My target object had same simple properties, but the generic List property was of an interface type.  Following is a simplified illustration of my source and target objects:

Source Object

Target Object

A cool thing about AutoMapper is that when it encounters a target object of an interface, it automatically generates a dynamic proxy class using Castle Dynamic Proxy.  This is usually the desired behavior when mapping to a non-existent target class.  In my case, however, the target class already existed, and dynamic proxy was just an overhead.  I tinkered with AutoMapper mappings to actually map to my existing target rather than generating a proxy:

Essentially what I am doing in my mapping is to first create a map between my source and target Orders objects. Once that’s done, I create a map between my source and target Customer objects but provide a custom map for the Orders property. In my custom map I simply use AutoMapper to map my source Orders property to target Orders property using the map definition I provided earlier (lines 1-2 above). This works out great and I get my expected target object without incurring the overhead of expensive proxies.

  1. August 19th, 2011 at 23:01 | #1

    I liked your article is an interesting technology
    thanks to google I found you

  1. No trackbacks yet.
 

Comment moderation is enabled. Your comment may take some time to appear.