Chapter 18. Mapping with AutoMapper

 

This chapter covers

  • Understanding AutoMapper
  • Configuring AutoMapper
  • Testing conventions
  • Applying formatters to eliminate duplicative code
  • Reducing markup to presentation only
  • Ridding views of complexity

The open source AutoMapper library is a convention-based object-to-object mapper. It takes source objects of one type and maps them to destination objects of another type. This is useful in many contexts, but we’ll use it to map from a domain model to the model objects our views display—the presentation model.

We call it convention based because it doesn’t depend on configuring each type’s member’s mapping, but instead relies on naming patterns and sensible defaults. You can check out the code and read more documentation at the AutoMapper website: http://automapper.codeplex.com.

18.1. Introducing AutoMapper

Given a source type and destination type, AutoMapper will assign values from source members, properties, and methods to corresponding members on the destination. It does this automatically, based on member names. Let’s look at a couple of quick examples to get started.

In the first example, we want to map from an object named Source to an object named Destination. Listing 18.1 shows these two classes. The names match up, so AutoMapper will simply map the value (and call ToString() on the Source.Number property).

Listing 18.1. An introductory mapping

18.2. Life before AutoMapper

18.3. AutoMapper basics

18.4. Summary