Skip to content

Conditional mapping

Bert Loedeman edited this page Aug 26, 2015 · 1 revision

AutoMapper allows you to add conditions to properties that must be met before that property will be mapped.

This can be used in situations like only mapping numbers which have a value >= 0.

class Person {
  age: number;
}

class ApiPerson { 
  age: number; // specified as -1 when empty in db
}

In the following mapping the property age will only be mapped if it is greater than or equal to 0 in the source object.

automapper.createMap('ApiPerson', 'Person')
  .forMember('age', (opts: AutoMapperJs.IMemberConfigurationOptions) => { 
                      opts.condition((sourceObject: any) => 
                        sourceObject.age >= 0) 
                    }
            );

Clone this wiki locally