Saturday, March 9, 2013

AutoMapper from a List to Class Properties

I just found AutoMapper, a tool I wish I'd had years ago. This can take any of you classes and translate them into another class. This would have been especially useful when I've had to get an object out of and EntityFramework, and add in additional properties before display, which happens quite often. The code for this is pretty simple, an well defined on their site.

I came across AutoMapper from my wife last week, and found it to be a perfect fit for on of my current issues. We're getting data from a Web service that has an Object and a lit of properties with their values, like the following.

I needed to easy map each property to my display object type. There is the option of using reflection (Looping through Object's properties in C# is an excellent example), and looping over each of the properties in my destination object, and filling them from values in the source object. Honestly, I did head down this path a bit, but realized I needed a more flexible solution.

It turns out our Web service may change in the next year or two where it returns properties in the same way my display object uses properties, but may have different names. AutoMapper makes it easy to put the translation logic in one place, and changes in the future will be minimal, and all take place in one location.

I'm now using the following to make the mapping work pretty easily:

The AutoMapper configuration should occur I one location, such as application start. Once we switch the Web service, the mapping can remove the specific property names, and only cover the properties where the display property name is different from the data source.


No comments: