AutoMapper - setting the final string to null actually makes it string.Empty

With the following display:

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

SomeStringProperty now the empty string is not zero (as expected)

This is mistake? How can I get it really null?

I see that opt.Ignore() will make it null, but I really want to make conditional null like the following, and the above simplified error (?) Prevents this

 Mapper.CreateMap<ObjectA, ObjectB>() .ForMember(dest => dest.SomeStringProperty, opt => opt.MapFrom(src => src.SomeOtherProp != null ? src.SomeOtherProp.Prop1 : null)) 
+3
source share
2 answers

I found the setting after looking at the source code ... Confirmation that this is not an error, but actually a custom setting.

When I set up my mappings.

 Mapper.Initialize(x => { x.AddProfile<UIProfile>(); x.AddProfile<InfrastructureProfile>(); x.AllowNullDestinationValues = true; // does exactly what it says (false by default) }); 
+6
source

you can define a map for strings using

 ITypeConverter<string, string> 

and when you convert return null if null. I think that by design you get an empty string, and I even find it natural and useful, but of course I am mistaken;)

I can provide more accurate code than the above on request, but consider that you know what you are doing.

+1
source

Source: https://habr.com/ru/post/1300203/


All Articles