How to handle a null property with Automapper

AutoMapper is a library that you can find now at GitHub. It’s the same one that has been hosted on CodePlex previously. The purpose of the AutoMapper library is to allow you to transfert value from an object to another. This is usefull when you are working with DTO object or when you need to map properties between your model and view model.

In this article, I’ll show you how to handle a null property. This case occur if you have a source object that has a null property and you want to have in the destination a value. A simple example would be that you have a User class that can have a classe Address. If this one is null, you may want to have in the destination an empty string or a default string value.

public class UserSource
	public Address Address{get;set;}

public class UserDestination
	public string Address{get;set;}

First, the mapping require to have the indication of your action.

AutoMapper.Mapper.CreateMap<UserSource, UserDestination>()
					.ForMember(dest => dest.Address
					, opt => opt.NullSubstitute("Address not found")

This indicate to map Address to Address (default behavior) but has the optional with NullSubstitute which let you specify an object to be used for the mapping if the source object is null. In the previous example, a string has been used but a default object could have been used without problem.

Here is how to call the mapper. The mapping is done without any other option than normal mapping.

var model = AutoMapper.Mapper.Map<UserSource, UserDestination>(user);
var models = AutoMapper.Mapper.Map<IEnumerable<UserSource>, IEnumerable<UserDestination>>(users);

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.