AutoMapper
Ever had those mundane tasks of mapping your entities to Data Transfer Objects for use in your service layer? While browsing the web the other day I found this great tool called AutoMapper which does a superb job in filling this void.
Writing mapping code is painful, creates more work and means you have more tests to write. This is where AutoMapper fits in.
Given the following entities:
public class Bank {
public string Name{ get; set; }
}
public class Customer {
public string Name { get; set; }
public Bank BankDetails{ get; set; }
}
public class CustomerDTO {
public string Name { get; set; }
public string BankName{ get; set; }
}
Now all we need to do is use the mapper in code like so:
AutoMapper.CreateMap<Customer, CustomerDTO>(); //setup the mappings
Customer newCustomer = new Customer() {Name = "test" };
CustomerDTO transformedCustomer = AutoMapper.Map<Customer, CustomerDTO>(newCustomer);
Brilliant! We now have a working CustomerDTO object and it even mapped our BankName for us without even setting up any custom mapping. Here is what AutoMapper can do for you:
- Matching property names
- Methods starting with the word “Get” automatically get mapped. e.g. GetAccountBalance() maps to AccountBalance
- Nested property names (Bank.Name maps to BankName, pretty sure this only works with PascalCase)
AutoMapper can also map collections for you too. One of the things to remember here is you don’t need to create a mapping for collections, just the element types.
For the testers amongst us I hear you say that you now can’t test your mappings like you could before with custom mapping code. Well there is an answer to this.
Mapper.AssertConfigurationIsValid();
This method will assert that all properties from the source will be mapped to something on the destination object. Mapping objects is now no longer painful!
Damn, that’s sweet, wish I’d have had this six months ago for my last project.
Great find!
Yeah I wish I had of known about it earlier as well. I might go through how to do custom mappings in another post too.
Automapper has reached 1.0 recently so go out and grab it!
AutoMapper 1.1 is out today with Silverlight 3 support.