How can I get AutoMapper to keep null from the source?
new MapperConfiguration(cfg => cfg.CreateMap<MyModel, MyModel>()
.ForMember(m => m.prop1, opt => opt.AllowNull())
.ForMember(m => m.prop1, opt => opt.NullSubstitute(null))
.ForMember(m => m.prop1, opt => opt.MapFrom(s => s.prop1))
).CreateMapper();
prop1 is a nullable, e.g. string[]
I always get the default for the type.
Null destination values and null collections are not allowed by default. You can set this on the configuration:
configuration.AllowNullCollections = true;
configuration.AllowNullDestinationValues = true;
You could also force this via a AfterMap configuration:
new MapperConfiguration(cfg => cfg.CreateMap<MyModel, MyModel>()
.AfterMap( (s,d) => d.prop1 = s.prop1 == null ? null : d.prop1 );
The automapper documentation reads as follows:
When mapping a collection property, if the source value is null AutoMapper will map the destination field to an empty collection rather than setting the destination value to null. This aligns with the behavior of Entity Framework and Framework Design Guidelines that believe C# references, arrays, lists, collections, dictionaries and IEnumerables should NEVER be null, ever.
You can change it using AllowNullCollections property:
Mapper.Initialize(cfg => {
cfg.AllowNullCollections = true;
cfg.CreateMap<Source, Destination>();
});
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