Wednesday 4 December 2013

AutoMapper



What's it?
A library to help reducing the time you spend on object-object mappings. E.g. from a Business Entity to a Data Transfer Object (DTO).

Considerations?
  • Always remember to create unit tests for your mappings to make sure AutoMapper works as you expect because it can be tricky when there are associations and complex objects and it might not behave as you'd expect.
Create the Map:

Mapper.CreateMap();

Perform the Map Between Two Objects

OrderDto dto = Mapper.Map(order);

Where to Create the Maps?

Create a Bootstrapper class and call it from the global.ascx; once per application.

Automatic Mapping Rules

Flattening:
  • order.Name <=> orderDto.Name
  • order.Customer.Name <=> orderDto.CustomerName
  • order.GetTotal() => orderDto.Total
Projection:
Mapper.CreateMap()
   .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.Date.Date))
Ignore a Property Mapping:
Mapper.CreateMap()
  .ForMember(dest => dest.SomeValuefff, opt => opt.Ignore());