Mapping Objects with AutoMapper

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.

Print | posted @ Thursday, February 19, 2009 4:26 AM

Comments on this entry:

Gravatar # re: Mapping Objects with AutoMapper
by Haacked at 2/19/2009 6:47 AM

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;}
}
  
Gravatar # re: Mapping Objects with AutoMapper
by scott at 2/19/2009 2:12 PM

@Phil: Currently no anon type support as far as I can tell.
  
Gravatar # re: Mapping Objects with AutoMapper
by Derek Morrison at 2/20/2009 2:12 PM

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.
  
Gravatar # re: Mapping Objects with AutoMapper
by scott at 2/20/2009 3:33 PM

@Derek - you are welcome!
  

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 7 and 2 and type the answer here: