Object Mappers - Merge Objects Together

The idea of mapping objects together is quite simple. It's like a "merge" two objects into one single object. AutoMapper is one tool that helps you achieve this and I will explain some use cases for it.

In most multi-layer systems, there are at least two instances of each database object (or entity). These "instances" are POCOs (Plain Old Class Objects) and are simply classes. These POCOs are used in different parts of the application and have different purposes.

POCOs

For example, a User POCO might be used in the repository layer of the system. The User class might look something like this.
  1. namespace App.Domain  
  2. {  
  3.     public partial class User  
  4.     {  
  5.         public int Id { getset; }  
  6.         public string UserName { getset; }  
  7.         public string FirstName { getset; }  
  8.         public string LastName { getset; }  
  9.         public string Email { getset; }  
  10.         public bool IsVisible { getset; }  
  11.     }  
  12. }  

The fields of the User POCO are drawn from the database and reflect the structure of the User table. However, when we want to use User data in the UI layer, we may want to incorporate more fields or decorations (annotations) to store additional information used within the UI. Therefore, we need another User POCO which we can modify and that does not impact the data layer POCO. These UI POCOs are often referred to as ViewModels.

ViewModels

General ViewModel best practice says that we should prefix the POCO name with ViewModel. For example, the data POCO would be called User, whereas the UI POCO would be called ViewModelUser. The ViewModelUser POCO might look something like this.

  1. namespace App.Web.Models  
  2. {  
  3.     public partial class ViewModelUser  
  4.     {  
  5.         [Required("This is required")]  
  6.         [DisplayBrand("Id")]  
  7.         public int Id { getset; }  
  8.       
  9.         [Required("This is required")]  
  10.         [StringLength(50, ErrorMessageResourceName="ValidatedMaxLength", ErrorMessageResourceType=typeof(Generic))]  
  11.         [Display("UserName")]  
  12.         public string UserName { getset; }  
  13.       
  14.         [Required("This is required")]  
  15.         [StringLength(50, ErrorMessageResourceName="ValidatedMaxLength", ErrorMessageResourceType=typeof(Generic))]  
  16.         [Display("FirstName")]  
  17.         public string FirstName { getset; }  
  18.       
  19.         [Required("This is required")]  
  20.         [StringLength(50, ErrorMessageResourceName="ValidatedMaxLength", ErrorMessageResourceType=typeof(Generic))]  
  21.         [Display("Surname")]  
  22.         public string LastName { getset; }  
  23.       
  24.         [Required("This is required")]  
  25.         [StringLength(100, ErrorMessageResourceName="ValidatedMaxLength", ErrorMessageResourceType=typeof(Generic))]  
  26.         [Display("Email")]  
  27.         [RegularExpressEmailAttribute]  
  28.         [DataType(DataType.EmailAddress)]  
  29.         public string Email { getset; }  
  30.       
  31.         [Required("This is required")]  
  32.         [Display("Active?")]  
  33.         public bool IsVisible { getset; }  
  34.     }  
  35. }  
You can see that the fields are essentially the same, but we can do more with them. Things that are specific to the UI portion of the application. If we were to just use one POCO throughout the entire system, the data POCO would have data annotation decorations for use in the UI layer which are no use in data layer. This adds to data transfer and increases the payload as POCOs are used throughout the system. The good old YAGNI approach (You Ain't Gonna Need It) should be in the back of your mind. If you don't need it, do not use it.

Now, a problem presents itself. When we are working with Controllers and Builders in our UI, we need to pass POCOs to the data layer. But our UI POCOs are not the same as our data POCOs. Even though we know that the User and ViewModelUser POCOs are essentially the same, our code does not know. So we need to tell it. How do we pass POCOs from our UI builders to our business builders when the parameter types do not match? This is where our Object Mapper comes into play.

We could do something like this.
  1. namespace App.Web.Models  
  2. {  
  3.     public class ViewModelUserBuilder : IViewModelUserBuilder  
  4.     {  
  5.         private readonly IUserBusiness _userBusiness;  
  6.   
  7.         public ViewModelUserBuilder(IUserBusiness userBusiness)  
  8.         {  
  9.             _userBusiness = userBusiness;  
  10.         }  
  11.   
  12.         public List<ViewModelUser> GetAllUsers()  
  13.         {  
  14.             List<User> model = _userBusiness.GetAllUsers().ToList();  //  returns a list of Users (data POCOs)  
  15.               
  16.             List<ViewModelUser> entities = new List<ViewModelUser>();   //  create a list of ViewModelUser (UI POCOs)  
  17.               
  18.             foreach(User user in model)  
  19.             {  
  20.                 //  loop through the data POCOs and create an instance of a UI POCO  
  21.                 ViewModelUser entity = new ViewModelUser(){  
  22.                     Id = user.Id,  
  23.                     UserName = user.UserName,  
  24.                     FirstName = user.FirstName,  
  25.                     LastName = user.LastName,  
  26.                     Email = user.Email,  
  27.                     IsVisible = user.IsVisible  
  28.                 }  
  29.                 entities.Add(entity);   //  Add the UI POCO to the list  
  30.             }  
  31.               
  32.             return entities;    //  return the UI POCO list for use in the UI  
  33.         }  
  34.     }  
  35. }  

Object Mapper

That seems like a lot of work, right? AutoMapper can make that whole process so much easier. It's as simple as creating an instance of each object (or list of objects), passing them into the mapping engine and returning the transformed object(s). Let me show you the above code using AutoMapper.

  1. namespace App.Web.Models  
  2. {  
  3.     public class ViewModelUserBuilder : IViewModelUserBuilder  
  4.     {  
  5.         private readonly IUserBusiness _userBusiness;  
  6.   
  7.         public ViewModelUserBuilder(IUserBusiness userBusiness)  
  8.         {  
  9.             _userBusiness = userBusiness;  
  10.             Mapper.CreateMap<ViewModelUser, User>();  
  11.             Mapper.CreateMap<User, ViewModelUser>();  
  12.         }  
  13.   
  14.         public List<ViewModelUser> GetAllUsers()  
  15.         {  
  16.             var entities = new List<ViewModelUser>();  
  17.             var model = _userBusiness.GetAllUsers().ToList();  
  18.             entities = Mapper.Map(model, entities); //  Let automapping "merge" the two objects  
  19.             return entities;  
  20.         }  
  21.     }  
  22. }  
That's much easier, right?

The order that you pass the POCOs into the Mapper.Map method does matter. The POCO on the left is the source type, and the one on the right is the destination type and the mapping works because both POCOs have the same field names. So, the mapping looks in the source POCO, then looks in the destination POCO for a corresponding field. If it finds a match, it merges the data from the source into the destination. It does not alter the source, so you can still use it if you want. But the destination POCO is presented in a useful way for you to work with.

Till next time .