OdeToCode IC Logo

Mapping Objects with AutoMapper

Thursday, February 19, 2009

At the end of last year I finished a project that required a fair amount of object-to-object mapping. Unfortunately, Jimmy Bogard didn’t release AutoMapper until this year, so I had to write a pile of object-to-object mapping goo on my own.

AutoMapper is a convention based mapper. Let’s say you have an object implementing an interface like this…

public interface IPatientDetailView
{
    string Name { get;  set; }
    IEnumerable<Procedure> Procedures { get;  set; }
    // ...         
}

…but all of the data you need to pump into the object is in a different type:

public class PatientDetailData
{
    public string Name { get; set; }
    public IEnumerable<Procedure> Procedures { get;  set; }
    // ...

}

With AutoMapper you just need a one time configuration:

Mapper.CreateMap<PatientDetailData, IPatientDetailView>();

Then moving data over is ridiculously easy:

Mapper.Map(patientData, patientView);

AutoMapper has a number of neat tricks up its sleeve. The flattening feature, for instance, can move data from a hierarchical object graph to a “flattened” destination. But what if your property names don’t match? Then you can take advantage of a fluent API to describe how AutoMapper should move the data. For example, moving data from the following type …

public class ProcedureData
{
    public string PatientName { get; set; }
    public IEnumerable<Procedure> Procedures { get;  set; }
    // ...

}

… will require a bit of configuration for AutoMapper to know where to put the patient name:

Mapper.CreateMap<ProcedureData, IPatientDetailView>()
        .ForMember(destination => destination.Name,
                   options => options.MapFrom(
                        source => source.PatientName));

For other AutoMapper features it’s best to peruse the tests. There are extensibility hooks, like custom formatters and resolvers, and support for different profiles. Check it out.