Reputation: 5162
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
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
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
Reputation: 24569
Try
AutoMapper.Mapper.Initialize(c =>
{
c.AllowNullCollections = true;
});
Upvotes: 2