Automapper returning an empty collection, I want a null

c0D3l0g1c picture c0D3l0g1c · Feb 9, 2016 · Viewed 11.2k times · Source
public class Person
{
   Name { get; set; }
   IEnumerable<Address> Addresses { get; set; }
}

public class PersonModel
{
   Name { get; set; }
   IEnumerable<AddressModel> Addresses { get; set; }
}

If I map Person to PersonModel like so:

Mapper.DynamicMap<Person, PersonModel>(person);

If the Addresses property on Person is null they are mapped on PersonModel as an empty Enumerable instead of null.

How do I get PersonModel to have null Addresses instead of an empty Enumerable?

Answer

Kirill Rakhman picture Kirill Rakhman · Jan 31, 2018

The simple answer is to use AllowNullCollections:

AutoMapper.Mapper.Initialize(cfg =>
{
    cfg.AllowNullCollections = true;
});

or if you use the instance API

new MapperConfiguration(cfg =>
{
    cfg.AllowNullCollections = true;
}