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.


Comments
Haacked Thursday, February 19, 2009
Can you map anonymous types somehow? For example,

I want to map:

new {foo = 123, bar = "test"}

to

public interface IFoo {
int foo {get;set;}
string bar {get;set;}
}
scott Thursday, February 19, 2009
@Phil: Currently no anon type support as far as I can tell.
Derek Morrison Friday, February 20, 2009
Thanks thanks thanks! I was just thinking about diving into an implementation of this myself, and you probably saved me a good bit of work.
scott Friday, February 20, 2009
@Derek - you are welcome!
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!