I am having trouble getting Automapper 4.2.1 to allow type matching, where the destination value may be null depending on the original value.
Older versions of Automapper allowed the AllowNullDestination flag to be set through the Mapper configuration, but I cannot find an equivalent recipe for the new version, and the old configuration mechanism through the static Mapper object seems to be deprecated.
I tried the following without success:
- Mapper.Configuration.AllowNullDestinationValues = true;
- Mapper.AllowNullDestinationValues = true;
- Mapper.Initialize (with => c.AllowNullDestinationValues = true);
Here is a simple test case demonstrating the problem. This does not execute on the last line with an AutoMapperMappingException , since the Substitute method returns null. I would like both comparisons to be successful.
I would rather avoid using .ForMember in the solution, since in the real script that I am trying to solve, the mapping between bool and 'object' (actually a custom class) should apply across the entire tree of objects.
Although there are several similar questions in StackOverflow, I did not find one that relates to the latest version of Automapper.
Thanks in advance for any suggestions.
using AutoMapper;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AutoMapperTest
{
[TestClass]
public class ExampleTest
{
[TestMethod]
public void NullDestinationCanBeMapped()
{
var mapper = new MapperConfiguration(configuration =>
{
configuration.CreateMap<Source, Target>();
configuration.CreateMap<bool, object>()
.Substitute(i => i ? null : new object());
}).CreateMapper();
var target1 = mapper.Map<Source, Target>(new Source {Member = false});
Assert.IsNotNull(target1.Member);
var target2 = mapper.Map<Source, Target>(new Source {Member = true});
Assert.IsNull(target2.Member);
}
}
public class Source
{
public bool Member { get; set; }
}
public class Target
{
public object Member { get; set; }
}
}
source
share