Wednesday, October 7, 2015

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:
1
2
3
4
5
6
7
8
9
10
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.
1
2
3
4
5
6
7
8
9
10
11
12
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:
1
2
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.

No comments:

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts

DotNetJalps