Programming Languages Hacks

Importanti regole per linguaggi di programmazione rilevanti come Java, C, C++, C#…

  • Subscribe

  • Lettori

    I miei lettori abituali

  • Twitter

Automapper: Ignore All Not Mapped Properties

Posted by Ricibald on July 19th, 2013

Normally in automapper you’ll write something like this:

Mapper.CreateMap<MoveEntity, MoveEntityDto>()
       .ForMember(dest => dest.PrimaryOriginTransferee, opt => opt.Ignore())
       .ForMember(dest => dest.PrimaryDestinationTransferee, opt => opt.Ignore())
       .ForMember(dest => dest.Customer, opt => opt.Ignore())
       .ForMember(dest => dest.DestinationAddress, opt => opt.Ignore())
       .ForMember(dest => dest.OriginAddress, opt => opt.Ignore())
       .ForMember(dest => dest.Order, opt => opt.Ignore())
       .ForMember(dest => dest.Shipment, opt => opt.Ignore())
       .ForMember(dest => dest.SourceSystemName, opt => opt.Ignore());

To ignore all not-mapped properties just use this extension method:

Mapper.CreateMap<MoveEntity, MoveEntityDto>()
       .IgnoreAllNonExisting();

Here the source code:

    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;
    }

Leave a Reply

You must be logged in to post a comment.