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:
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.