AutoMapper is a convention-based object-object mapper as described by the AutoMapper project homepage (http://www.codeplex.com/AutoMapper).

Basically it will map properties between two different objects (different types). If the name of the properties are the same it just works. It works with lists and nested types. All you need to do is initiate the mapping and then do the actual mapping. Here’s an example when mapping from an instance of type User to a UserViewModel instance.

   1: Mapper.CreateMap<User, UserViewModel>;
   2: User user = new UserRepository().Get(1);
   3: UserViewModel userViewModel = Mapper.Map<User, UserViewModel>();

If the structure/name isn’t something that AutoMapper can figure out how to map then it’s possible to add manual mappings with lambda expressions. For example if the User has a Telephone type with a property called PhoneNumber and the UserViewModel has a basic string property called Phone:

   1: Mapper.CreateMap<User, UserViewModel>()
   2:     .ForMember(viewModel => viewModel.Phone, opt => opt.MapFrom(user => user.Telephone.PhoneNumber)));
   3:  
   4:  

Very cool stuff indeed. I introduced AutoMapper in one of the projects I’m currently working on and since it was mostly 1-1 mapping that was done, I reduced over 600 lines of code in two hours in the project. Since I just replaced the body of my mapper methods with the call to AutoMapper that meant that all the unit tests I had written could verify that everything worked as before.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading