How can a coder automatically map database objects to domain objects? Find out in this blog on Object Mapping!
Some years ago, I was working on a project that had a rather extensive data model (200+ tables). While working on the many data retrieval methods, I spent many hours writing code to map database objects to domain objects. This type of code is not exciting – in fact, it’s rather boring to write!
In the throes of my boredom, I started thinking about a way to automate this task and then figured – if I was thinking about it, surely someone else had to. A quick Google search led me to AutoMapper.
What is AutoMapper? According to its creator, “AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper’s established convention, almost zero configuration is needed to map two types.” (http://automapper.org/)
AutoMapper, at its simplest, allowed me to map my source data objects to my destination domain objects using one line of code:
To execute the mapping:
ObjectTypeDestination obj = Mapper.Map(sourceInstance);
For simple mapping scenarios, that’s all it takes. AutoMapper provides a large number of options that allow you to flatten object models during the mapping process and many more advanced features to handle pretty much any mapping challenge you might face. It is one of the most useful tools I’ve discovered.
For more information about AutoMapper: