Automapper returning an empty collection, I want a null

So there are probably several ways you can accomplish this with Automapper, and this is just one:

Mapper.CreateMap<Person, PersonMap>()
   .AfterMap( (src, dest) => dest.Addresses = dest.Addresses?.Any() ? dest.Addresses : null );

This code uses the new c# ?. operator for null safety, so you might need to remove that and check for null if you can't use that feature in your code.


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;
}

In addition to setting AllowNullCollections in the mapper configuration initialization (as noted in this answer), you have the option to set AllowNullCollections in your Profile definition, like this:

public class MyMapper : Profile
{
    public MyMapper()
    {
        // Null collections will be mapped to null collections instead of empty collections.
        AllowNullCollections = true;

        CreateMap<MySource, MyDestination>();
    }
}