AutoMapper: “Ignore the rest”?

2020-01-22 13:05发布

Is there a way to tell AutoMapper to ignore all of the properties except the ones which are mapped explicitly?

I have external DTO classes which are likely to change from the outside and I want to avoid specifying each property to be ignored explicitly, since adding new properties will break the functionality (cause exceptions) when trying to map them into my own objects.

16条回答
叛逆
2楼-- · 2020-01-22 13:46

In version of 3.3.1 you simply can use IgnoreAllPropertiesWithAnInaccessibleSetter() or IgnoreAllSourcePropertiesWithAnInaccessibleSetter() methods.

查看更多
Fickle 薄情
3楼-- · 2020-01-22 13:53

I've been able to do this the following way:

Mapper.CreateMap<SourceType, DestinationType>().ForAllMembers(opt => opt.Ignore());
Mapper.CreateMap<SourceType, DestinationType>().ForMember(/*Do explicit mapping 1 here*/);
Mapper.CreateMap<SourceType, DestinationType>().ForMember(/*Do explicit mapping 2 here*/);
...

Note: I'm using AutoMapper v.2.0.

查看更多
淡お忘
4楼-- · 2020-01-22 13:55

I know this is an old question, but @jmoerdyk in your question:

How would you use this in a chained CreateMap() expression in a Profile?

you can use this answer like this inside the Profile ctor

this.IgnoreUnmapped();
CreateMap<TSource, Tdestination>(MemberList.Destination)
.ForMember(dest => dest.SomeProp, opt => opt.MapFrom(src => src.OtherProp));
查看更多
在下西门庆
5楼-- · 2020-01-22 13:56

There's been a few years since the question has been asked, but this extension method seems cleaner to me, using current version of AutoMapper (3.2.1):

public static IMappingExpression<TSource, TDestination> IgnoreUnmappedProperties<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var typeMap = Mapper.FindTypeMapFor<TSource, TDestination>();
    if (typeMap != null)
    {
        foreach (var unmappedPropertyName in typeMap.GetUnmappedPropertyNames())
        {
            expression.ForMember(unmappedPropertyName, opt => opt.Ignore());
        }
    }

    return expression;
}
查看更多
登录 后发表回答