tags:

views:

532

answers:

2

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))
+1  A: 

you could define map for strings using

ITypeConverter<string, string>

and when you convert return null if null. I think it is by design that you get an empty string and I even find this natural and useful myself but I may of course be wrong ;)

I can provide more precise code than above upon request but reckon you know what you're doing.

dove
the issue is coming from the MapFrom expression, when that gets a null value, it returns string.Empty. If I implement a custom TypeConverter for string -> string it will return null, but then the MapFrom will convert that to string.empty.
Jon Erickson
+2  A: 

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)
});
Jon Erickson
+1 good one, think you can award yourself answer.
dove
lol, not bug then. I just confirmed with a simple test.
Jimmy Bogard