Thursday, May 10, 2012

Automapper Ignore All Non Existing Properties

Code Snippet
  1. public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>
  2.                                             (this IMappingExpression<TSource, TDestination> expression)
  3.         {
  4.             var sourceType = typeof(TSource);
  5.             var destinationType = typeof(TDestination);
  6.             var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType));
  7.             foreach (var property in existingMaps.GetUnmappedPropertyNames())
  8.             {
  9.                 expression.ForMember(property, opt => opt.Ignore());
  10.             }
  11.             return expression;
  12.         }

No comments: