Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve null on mapping - don't create default for type

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.

like image 786
Benjamin E. Avatar asked Oct 25 '25 04:10

Benjamin E.


2 Answers

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 );
like image 102
Martin Zikmund Avatar answered Oct 27 '25 20:10

Martin Zikmund


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>();
});
like image 43
smolchanovsky Avatar answered Oct 27 '25 19:10

smolchanovsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!