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?
Map always returns null when source object is null #3267.
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.
AutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.
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();
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>(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With