Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper returning an empty collection, I want a null

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?

like image 286
c0D3l0g1c Avatar asked Feb 09 '16 13:02

c0D3l0g1c


People also ask

Can Mapper return null?

Map always returns null when source object is null #3267.

How do I ignore property in AutoMapper?

So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.

Can AutoMapper map collections?

AutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.

How do I test AutoMapper mappings?

To test our configuration, we simply create a unit test that sets up the configuration and executes the AssertConfigurationIsValid method: var configuration = new MapperConfiguration(cfg => cfg. CreateMap<Source, Destination>()); configuration. AssertConfigurationIsValid();


2 Answers

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; } 
like image 180
Kirill Rakhman Avatar answered Sep 21 '22 07:09

Kirill Rakhman


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>();     } } 
like image 33
Mike Avatar answered Sep 24 '22 07:09

Mike