人本善良

导航

12.AutoMapper 之Null替换(NullSubstitution)

 

Null 替换(Null Substitution)

Null 替换允许当源类型成员在成员链任何位置为Null时给目标成员提供一个备用的值。这意味着目标成员不再映射为Null而是你提供的备用值。

var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Dest>()
    .ForMember(destination => destination.Value, opt => opt.NullSubstitute("Other Value")));

var source = new Source { Value = null };
var mapper = config.CreateMapper();
var dest = mapper.Map<Source, Dest>(source);

dest.Value.ShouldEqual("Other Value");

source.Value = "Not null";

dest = mapper.Map<Source, Dest>(source);

dest.Value.ShouldEqual("Not null");

在目标类型之后任何映射/转换都是以源成员类型来进行的。

posted on 2019-06-20 17:11  简简单单2018  阅读(315)  评论(0编辑  收藏  举报