Advertisements
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?
>Solution :
It’s by design.
You can change the default if you wish:
var configuration = new MapperConfiguration(cfg => {
cfg.AllowNullCollections = true;
cfg.CreateMap<Source, Destination>();
});
Or change it for one mapping (though, I didn’t try this one).
https://docs.automapper.org/en/stable/Lists-and-arrays.html#handling-null-collections