Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save janierdavila/ea30eb9acd4b0030db33 to your computer and use it in GitHub Desktop.

Select an option

Save janierdavila/ea30eb9acd4b0030db33 to your computer and use it in GitHub Desktop.
public static class AutoMapperExtensions
{
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;
}
}
// USAGE:
Mapper.CreateMap<SourceType, DestinationType>()
.ForMember(prop => x.Property, opt => opt.MapFrom(src => src.OtherProperty))
.IgnoreAllNonExisting();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment