Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

automapper

Is it possible to configure AutoMapper to return a new instance of the destination type if the source object is null?

Source source = null;
Dest d1 = AutoMapper.Mapper.Map<Source, Dest>(source);
// d1 == null

// I'm looking for a way to configure AutoMapper to
// eliminate this code:
Dest d2 = AutoMapper.Mapper.Map<Source, Dest>(source) ?? new Dest();
like image 438
M4N Avatar asked Aug 04 '10 16:08

M4N


2 Answers

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).

like image 181
M4N Avatar answered Sep 22 '22 12:09

M4N


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)));
like image 35
Vijai Avatar answered Sep 21 '22 12:09

Vijai