简体   繁体   中英

How to map empty strings as null with automapper?

I need to map empty strings from source model as null to destination model. 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(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部分提取到可以调用的扩展方法中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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