AutoMapper: create instance of destination type if source == null

孤者浪人 提交于 2019-12-04 00:15:42

Answering my own question (partially):

AutoMapper has a configuration property named AllowNullDestinationValues which is set to true by default. By setting this to false, I get the behavior shown in the question, e.g:

Mapper.Configuration.AllowNullDestinationValues = false;

//...

Source source = null;
Dest d = AutoMapper.Mapper.Map<Source, Dest>(source);
// d is now a new instance of Dest

This solution works OK for simple types, where source and destination types map well. I still have some issues with complex mappings (I will update the question to show an example).

You can also use .NullSubstitute() to replace NULL value to some custom value for any property in Automapper, e.g.:

CreateMap<SMModel, VM_SMModel>()
                    .ForMember(d => d.myDate, o => o.NullSubstitute(new DateTime(2017,12,12)));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!