Well-designed software applications are typically layered to provide a maximum isolation between the logical parts of application and often require transformation of data from layer to layer.

AutoMapper facilitates such transformations providing a convention-first approach for mapping an object of one type into an object of some other type. Convention-first, in this case, means zero configuration for the cases when the source and the target classes has properties with the same names. For other cases, AutoMapper provides a rich API to customize mapping configuration.

Use of AutoMapper eliminates routine, repetitive and error prone list of copy instructions. Automapper allows to define a mapping, which can be reused in the code multiple times to do a one line transformation. Common use cases for the Automapper library include mapping between Data Transfer Model and Model or between Model and ViewModel.

When two types are aligned (properties which are required to be transferred have the same names), configuration is as simple as the following one line of code

Mapper.Initialize(cfg=>cfg.CreateMap());

The usage is simple as well

OrderDto dto = Mapper.Map(order);

While the usage code stays the same all the time, configuration may become more complicated. For example, the following code demonstrates an action which will be called before the mapping and a custom mapping rule for one of the class members.

Mapper.Initialize(cfg=>cfg.CreateMap()
                          .BeforeMap((order, dt)=> {order.DateTime = DateTime.UtcNow;})
                          .ForMember(o=>o.CustomerName, x=>x.UseValue("admin")));

AutoMapper supports automatic flattening – mapping between a property and a class hierarchy. For example, the value of a Name property of an object referenced by a Customer property of Order may be automatically mapped (if compatible) to a CustomerName property of OrderDto.

Any time, when conventions do not satisfy the needs of the application, they can be replaced by the explicit configuration.

blog comments powered by Disqus