I was working on a project that required mapping values to complex objects when I say complex the target object was a large collection of multiple objects several levels deep. Some of the objects to which the values had to be mapped were several levels down. The task of finding the correct objects or directly assigning values to the properties of objects was tedious, especially if it had to be done over and over again. This problem led me to create the object auto mapper. During the course of this post, the target is the object you are operating on or mapping the values to and the source is the object from which the values are copied.
Auto mapper uses reflection to index all the objects on which it is operating. After the index is created, the algorithm can then identify the target object on which to operate based on the type of the source object. Once the target object is found then the algorithm sweeps through the properties of the target to identify all the properties that have a public set on them. The algorithm will now set the values of the properties.
Some of the features of my Auto mapper are
- Automatically finds the first occurrence of an object type and maps them.
- If there are multiple objects of the same type in the target object, you can specify the property name to map it to.
- If the object already has some data in it, this will preserve the existing once and map only the new once.
- If the target property is
null, the auto mapper can initialize the property and map the values.
- If the target property is a
Array, it can initialize if the property is
nullor if it already has values the new values get added to it.
Let’s see some code!