简体   繁体   English

如何使用自动映射器将空字符串映射为null?

[英]How to map empty strings as null with automapper?

I need to map empty strings from source model as null to destination model. 我需要将空字符串从源模型映射为null到目标模型。 At first I used next profile for this: 首先,我为此使用了下一个配置文件:

public class MyProfile:Profile
{
    public MyProfile()
    {
       CreateMap<SrcModel, DestModel>()
       .ForMember(dst => dst.Field1, opt => 
       {
          opt.Condition(src => !string.IsNullOrEmpty(src.src_Field1));
          opt.MapFrom(src => src.src_Field1)
       })
       //.......
       //same for other 15 fields
    }
}

But duplicating same logic looks not very good and it's hard to modify it. 但是复制相同的逻辑看起来不是很好,并且很难对其进行修改。

Also I have tried to create special map for string like this: 我也试图为这样的字符串创建特殊的映射:

CreateMap<string, string>().ConvertUsing(src => string.IsNullOrEmpty(src) ? 
null : src)

But such string map has impact on all my maps, but I need such logic only for several maps, not for all. 但是这样的字符串映射对我所有的映射都有影响,但是我只需要对几个映射使用这种逻辑,而对所有映射都不需要。

I also have tried to use ForAllMembers method: 我也尝试过使用ForAllMembers方法:

... .ForAllMembers(opt => opt.Condition();

But there is no way do define type of source member, to cpecify some condition for strings. 但是无法定义源成员的类型来为字符串指定某些条件。

What is the best way to define some common mapping logic for several members of same type for one map? 为一个映射为多个相同类型的成员定义一些通用映射逻辑的最佳方法是什么?

只需重复一下逻辑,我要做的最多就是将Condition部分提取到可以调用的扩展方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM