Use a custom function when mapping one property to another with Automapper

Automapper is a handful tool for mapping the properties of two different type objects together. Such mappings are very common when you are dealing with a multi-tier architecture in your program. For example you want to map the entity object, which contains data from the database, with the UI-model object of your WebApi action.

For basic mapping examples refer to the Automapper documentation. In this article we will consider the following advanced example:

  • Your entity model contains a property with a non-serialized string that you store in a table of your database

  • Based on some condition checking, you want to or do not want to deserialize this string and store it into a property of different type of your UI-model object

For that you need a mapping between two properties of different type and also a function that runs every time to do this transformation:

First define the mapping between the two objects by using the CreateMap function and specify the custom mapping between the two properties by using the ForMember function. The property ObjectAsString contains the serialized object that we got from the database:

1
2
3
4
CreateMap<EntityObj, UIModelObj>().ForMember(source => source.ObjectAsString, target => target.MapFrom(entity => 
    entity.Firstname == "Christos" && entity.Lastname == "Monogios"
? DeserializeObjectAsString(entity.ObjectAsString)
: null));

We are checking the Firstname and Lastname properties to identify if we are going to deserialize the string of not.

If yes, then we call our DeserializeObjectAsString function and add our custom code to it. This function returns an object with the type defined in our UI-model object. The implementation of this function could look like that:

1
2
3
4
5
6
public static UIModelObjectType DeserializeObjectAsString(string objectAsString)
{
    // Code for deserializing

    return new UIModelObjectType();
}
comments powered by Disqus