This is a follow up to a previous question: Automapper sets an array property to a zero-length array rather than null
private class Fiz
{
public string Str { get; set; }
public string[] StrArr { get; set; }
public object[] ObjArr { get; set; }
}
private class Baz
{
public string Str { get; set; }
public string[] StrArr { get; set; }
public object[] ObjArr { get; set; }
}
[TestMethod]
public void ShouldAllowMapArrayToNull()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = true;
cfg.CreateMap<Fiz, Baz>().ForMember(b => b.Str, opt => opt.Ignore())
//.ForMember(b => b.StrArr, opt => opt.MapFrom(f => f.StrArr))
//.ForMember(b => b.ObjArr, opt => opt.MapFrom(f => f.ObjArr))
.ForMember(b => b.StrArr, opt => opt.ResolveUsing(f => f.StrArr))
.ForMember(b => b.ObjArr, opt => opt.ResolveUsing(f => f.ObjArr))
});
var mapper = config.CreateMapper();
var fiz = new Fiz
{
Str = null,
StrArr = null,
ObjArr = null
};
var baz = mapper.Map<Fiz, Baz>(fiz);
Assert.AreEqual(null, baz.Str,"string mapping to null");
Assert.AreEqual(null, baz.StrArr,"string arr mapping to null");
Assert.AreEqual(null, baz.ObjArr,"object arr mapping to null");
}
In the example above, baz is as follows: baz.Str == null, baz.StrArr == string[0], baz.ObjArr == object[0]
Despite using the suggested solutions in the original question, there seems to be no way of getting a mapping of the destination array to null, despite the source arrays being null themselves.
Is there a way to solve this (i.e. allow actual mapping of dest parameters to null), or is this a known limitation?
Edit: cfg.AllowNullCollections = true;
Solves this problem (thanks to MosheG), however this will apply to ALL the maps created under the mapper configuration. Is there a way to allow null instead of an empty array on a SINGLE created map?