Have you ever created a block-level element (e.g. a div), whose only contents are floating elements – only to find that your block-level element doesn’t stretch down to contain it’s children? Well, I have, and it’s a problem that always annoys me because I can never bring to mind the easiest way of fixing it.
The simplest solution is to use “overflow:hidden” in the style of your parent element, however this doesn’t work for all browsers scenarios. So, for a much more comprehensive description of the problem, as well as a number of approaches you can use to solve it, check out this post.
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!