且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果对象为空,如何将 Automapper 9 配置为忽略对象属性,但如果不为空则映射

更新时间:2022-03-23 17:00:14

移除 ReverseMap() ,然后尝试使用 AutoMapper 条件映射 并使用 ForPath 而不是 ForMember 嵌套子对象属性:

Remove ReverseMap() ,then try to use AutoMapper Conditional Mapping and use ForPath instead of ForMember for nested child object properties:

CreateMap<SomeEntityViewModel, SomeEntity>()
    .ForPath(
            m => m.NestedObject.StringValue, 
            opt => {                         
                     opt.Condition(
                        s => s.DestinationMember != null && s.DestinationMember != "" 
                     );
                     opt.MapFrom(s => s.NestedObjectStringValue);
                   }
            );

IntValue.

更新

因此,如果 NestedObject 为空,您不想将 SomeEntityViewModel 中的值映射到它.如果 NestedObject 不为空,则映射有效.

So, if the NestedObject is null, you do not want to to map the value from SomeEntityViewModel to it. If the NestedObject is not null,mapping works.

请参考下面使用AfterMap

CreateMap<SomeEntityViewModel, SomeEntity>()
             .ForMember(q => q.NestedObject, option => option.Ignore())
             .AfterMap((src, dst) => {
                     if(dst.NestedObject != null)
                     {
                     dst.NestedObject.StringValue = src.NestedObjectStringValue;
                     }

                 });