3
votes

I'm seeing some very strange behaviour in Automapper when mapping from a object with a single Nullable<bool> property. I currently have it set up like this:

public class MyViewModel
{
    public bool? IsAThing { get; set; }
}

public class MyEntity
{
    public bool? IsAThing { get; set; }

    public bool? HasAnotherThing { get; set; }

    public string AnotherThing { get; set; }

    // Lots of other fields
}

with the following mapping profile (with a similar reverse mapping):

CreateMap<MyViewModel, MyEntity>()
    .ForMember(x => x.IsAThing, opt => opt.MapFrom(y => y.IsAThing))
    .ForAllOtherMembers(opt => opt.Ignore());

However if I try to do the following:

var config = new AutoMapperConfig().Configure();
var mapper = config.CreateMapper();

var source = new MyViewModel { IsAThing = true };
var dest = new MyEntity();

mapper.Map(source, dest);

dest.IsAThing is null. The mapping profile is the only place where MyViewModel is declared as a mapping source. Strangely, if I declare the class

public class AnotherThingViewModel
{
    public bool? HasAnotherThing { get; set; }
    public string AnotherThing { get; set; }
}

And do the following test:

var source = new AnotherThingViewModel { HasAnotherThing = true };
var dest = new MyEntity();
mapper.Map(source, dest);

dest.HasAnotherThing is true as expected!

Obviously I have no idea what's going on here so has anyone seen anything like this before, or knows of any bugs in Automapper that might cause this?

1
Can't reproduce this with provided code and last (6.1.1) version of automapper nuget package (that is - dest.IsAThing is true and not null). - Evk
Please edit your question to include a MCVE so we can see/test the source code you have. - Progman

1 Answers

3
votes

I figured it out, I had CreateMap<MyViewModel, MyEntity>().ForAllMembers(opt => opt.Ignore()) elsewhere in my mapping configuration!