Auto-ignore non existing destination properties with AutoMapper

By default, AutoMapper tries to map all properties of the source type to the destination type. If some of the properties are not available in the destination type it will not throw an exception when doing the mapping. However it will throw an exception when you are using ValidateMapperConfiguration().

Imagine if we have the following two types:

class SourceType
{
    public string FirstName { get; set; }
}

class DestinationType
{    
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

ValidateMapperConfiguration() will throw the following exception when you Map SourceType to DestinationType:

AutoMapper.AutoMapperConfigurationException : The following 1 properties on DestinationType are not mapped: 
	LastName 
Add a custom mapping expression, ignore, or rename the property on SourceType.

You can override this behavior by making a small extension method to ignore all properties that do not exist on the target type.

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var sourceType = typeof(TSource);
    var destinationType = typeof(TDestination);
    var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
        && x.DestinationType.Equals(destinationType));
    foreach (var property in existingMaps.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}

Then it is possible to do the mapping as follows:

Mapper.CreateMap<SourceType, DestinationType>()
    .IgnoreAllNonExisting();

It is also possible to customize this method to your needs, by specifically ignoring properties which have a protected or private setter, for example.

Advertisements