Adam Levitt
Adam Levitt

Reputation: 10476

AutoMapper Skip All Null Properties, and then Allow some nulls

Is there a way to tell AutoMapper to skip all null properties (since my object has 50 properties) and then allow certain properties to be null afterwords?

In otherwords, I'd rather not "whitelist" 49 properties that should be skipped. I'd rather default them ALL to be skipped, and then "whitelist" the one to ALLOW nulls.

The first part might of course look like this I imagine.

Mapper.CreateMap<MyClassA, MyClassB>()                
.ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));

Upvotes: 3

Views: 782

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

You can use AfterMap to map certain properties manually and skip all other null properties:

Mapper.CreateMap<MyClassA, MyClassB>()
      .AfterMap((a,b) => b.Foo = a.Foo) // will be mapped if Foo is null
      .ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));

Upvotes: 4

Related Questions