猿问

AutoMapper:“忽略其余的”?

AutoMapper:“忽略其余的”?

有没有办法告诉AutoMapper忽略除明确映射的属性之外的所有属性?

我有外部DTO类可能会从外部更改,我想避免指定要显式忽略的每个属性,因为添加新属性会在尝试将它们映射到我自己的对象时破坏功能(导致异常)。


慕哥9229398
浏览 1661回答 3
3回答

红糖糍粑

我已经更新了Can Gencer的扩展,不会覆盖任何现有的地图。public&nbsp;static&nbsp;IMappingExpression<TSource,&nbsp;TDestination>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;IgnoreAllNonExisting<TSource,&nbsp;TDestination>(this&nbsp;IMappingExpression<TSource,&nbsp;TDestination>&nbsp;expression){ &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;sourceType&nbsp;=&nbsp;typeof&nbsp;(TSource); &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;destinationType&nbsp;=&nbsp;typeof&nbsp;(TDestination); &nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;existingMaps&nbsp;=&nbsp;Mapper.GetAllTypeMaps().First(x&nbsp;=>&nbsp;x.SourceType.Equals(sourceType)&nbsp;&&&nbsp;x.DestinationType.Equals(destinationType)); &nbsp;&nbsp;&nbsp;&nbsp;foreach&nbsp;(var&nbsp;property&nbsp;in&nbsp;existingMaps.GetUnmappedPropertyNames()) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;expression.ForMember(property,&nbsp;opt&nbsp;=>&nbsp;opt.Ignore()); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;expression;}用法:Mapper.CreateMap<SourceType,&nbsp;DestinationType>() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.ForMember(prop&nbsp;=>&nbsp;x.Property,&nbsp;opt&nbsp;=>&nbsp;opt.MapFrom(src&nbsp;=>&nbsp;src.OtherProperty)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.IgnoreAllNonExisting();

慕婉清6462132

根据我的理解,问题是目标上的字段在源中没有映射字段,这就是为什么要寻找忽略那些非映射目标字段的方法。您可以简单地使用,而不是实现和使用这些扩展方法Mapper.CreateMap<destinationModel,&nbsp;sourceModel>(MemberList.Source);现在,automapper知道它只需要验证所有源字段是否已映射,而不是相反。您还可以使用:Mapper.CreateMap<destinationModel,&nbsp;sourceModel>(MemberList.Destination);
随时随地看视频慕课网APP
我要回答