Benjamin E.
Benjamin E.

Reputation: 5162

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.

Upvotes: 4

Views: 2548

Answers (3)

Martin Zikmund
Martin Zikmund

Reputation: 39072

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 );

Upvotes: 6

smolchanovsky
smolchanovsky

Reputation: 1863

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>();
});

Upvotes: 4

Roman Marusyk
Roman Marusyk

Reputation: 24569

Try

AutoMapper.Mapper.Initialize(c =>
{
    c.AllowNullCollections = true;
});

Upvotes: 2

Related Questions