4

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.

1
  • prop1 is an collection? Commented Apr 15, 2019 at 12:12

3 Answers 3

6

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 );
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

2

Try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.