DEV Community

Discussion on: Using AutoMapper with ASP.NET Core 3

Collapse
 
michaeljolley profile image
Michael Jolley

Oh yeah! All the basic collection types are supported so you can do anything like:

IEnumerable<Destination> ienumerableDest = mapper.Map<Source[], IEnumerable<Destination>>(sources);
ICollection<Destination> icollectionDest = mapper.Map<Source[], ICollection<Destination>>(sources);
IList<Destination> ilistDest = mapper.Map<Source[], IList<Destination>>(sources);
List<Destination> listDest = mapper.Map<Source[], List<Destination>>(sources);
Destination[] arrayDest = mapper.Map<Source[], Destination[]>(sources);

But in your example where the list is a property on another mapped object you might need one other thing. If that property could be null, you’ll want to add something to your configuration:

var configuration = new MapperConfiguration(cfg => {
    cfg.AllowNullCollections = true;
    cfg.CreateMap<Source, Destination>();
});

The AllowNullCollections will prevent null exception errors on collections. By default, AutoMapper behaves like Entity Framework in that it believes collection properties should never be null.

Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

I like to always initialize my collections, but thanks for this information.