Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper - setting destination string to null actually makes it string.Empty

Tags:

c#

automapper

With the following mapping:

Mapper.CreateMap<ObjectA, ObjectB>()
    .ForMember(dest => dest.SomeStringProperty, opt => opt.MapFrom(src => null))

SomeStringProperty is now empty string not null (as I would expect)

Is this a bug? How can I get it to actually be null?

I see that opt.Ignore() will make it null but I actually want to do a conditional null like the following and the above simplified bug(?) is preventing this

Mapper.CreateMap<ObjectA, ObjectB>()
    .ForMember(dest => dest.SomeStringProperty, opt => opt.MapFrom(src => src.SomeOtherProp != null ? src.SomeOtherProp.Prop1 : null))
like image 208
Jon Erickson Avatar asked Aug 06 '26 22:08

Jon Erickson


1 Answers

I found the setting after looking through the source code... Confirming that this is not a bug, but in fact a configurable setting.

When I configure my mappings..

Mapper.Initialize(x =>
{
    x.AddProfile<UIProfile>();
    x.AddProfile<InfrastructureProfile>();
    x.AllowNullDestinationValues = true; // does exactly what it says (false by default)
});
like image 96
Jon Erickson Avatar answered Aug 08 '26 13:08

Jon Erickson