有没有一种方法告诉AutoMapper忽略所有的属性,除了那些显式映射的?
我有可能从外部更改的外部DTO类,并且我希望避免显式地指定要忽略的每个属性,因为添加新属性将在尝试将它们映射到自己的对象时破坏功能(导致异常)。
有没有一种方法告诉AutoMapper忽略所有的属性,除了那些显式映射的?
我有可能从外部更改的外部DTO类,并且我希望避免显式地指定要忽略的每个属性,因为添加新属性将在尝试将它们映射到自己的对象时破坏功能(导致异常)。
当前回答
您可以使用ForAllMembers,而不是只覆盖所需 像这样
public static IMappingExpression<TSource, TDest> IgnoreAll<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
{
expression.ForAllMembers(opt => opt.Ignore());
return expression;
}
小心,它将忽略所有,如果你不添加自定义映射,它们已经被忽略,将无法工作
我还想说,如果你有AutoMapper的单元测试。你测试了所有的模型,所有的属性映射正确,你不应该使用这种扩展方法
你应该显式地写ignore
其他回答
您可以使用ForAllMembers,而不是只覆盖所需 像这样
public static IMappingExpression<TSource, TDest> IgnoreAll<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
{
expression.ForAllMembers(opt => opt.Ignore());
return expression;
}
小心,它将忽略所有,如果你不添加自定义映射,它们已经被忽略,将无法工作
我还想说,如果你有AutoMapper的单元测试。你测试了所有的模型,所有的属性映射正确,你不应该使用这种扩展方法
你应该显式地写ignore
我更新了Robert Schroeder对AutoMapper 4.2的答案。对于非静态映射器配置,我们不能使用mapper . getalltypemaps(),但表达式有一个对所需的TypeMap的引用:
public static IMappingExpression<TSource, TDestination>
IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
foreach (var property in expression.TypeMap.GetUnmappedPropertyNames())
{
expression.ForMember(property, opt => opt.Ignore());
}
return expression;
}
在3.3.1版本中,您可以使用IgnoreAllPropertiesWithAnInaccessibleSetter()或IgnoreAllSourcePropertiesWithAnInaccessibleSetter()方法。
当前(版本9)忽略目标类型中不存在的属性的解决方案是创建一个翻转映射并反转它:
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<TheActualDestinationType, TheActualSourceType>().ReverseMap();
});
The only infromation about ignoring many of members is this thread - http://groups.google.com/group/automapper-users/browse_thread/thread/9928ce9f2ffa641f . I think you can use the trick used in ProvidingCommonBaseClassConfiguration to ignore common properties for similar classes. And there is no information about the "Ignore the rest" functionality. I've looked at the code before and it seems to me that will be very and very hard to add such functionality. Also you can try to use some attribute and mark with it ignored properties and add some generic/common code to ignore all marked properties.