title: Patterns for mapping data between domain models
body: <p>This is a common thing that I have been needing to do recently and I was looking for any common patterns to make this a little easier.</p>
  
  <p>The main gist of it all is that I have some data models, which are modelled to satisfy the ORM and purely do CRUD operations to objects. These models are currently exposed via repositories/factories (dependant upon if its C or RUD).</p>
  
  <p>I then have a view model, which is a bit more readable, and is sprinkled with UI concerns, such as validation and mapping data between the view (this is an ASP.MVC scenario but this situation can be abstracted to most situations).</p>
  
  <p>So lets say I go to localhost/user/1, that should go and get me the user with an Id 1 in the DB and then display it on the UI. Ultimately this has to pull data down from the data domain and then map it to a ui model for display purposes.</p>
  
  <p>Here is an example scenario:</p>
  
  <pre><code>public class OrmUser
  {
      public int Id {get;set;}
      public string Name {get;set;}
      public IList&lt;Permission&gt; Permissions {get;set;}
  }
  
  public class UiUser
  {
      [Required]
      public int Id {get;set;}
      [Required]
      public string Name {get;set;}
      public bool IsUserAdmin {get;set;}
  }
  
  public class UserMapper : IMapper&lt;UiUser&gt;
  {
      public UiUser Get(int id)
      {
          var ormUser = UserRepository.Get(id);
          var uiUser = new UiUser
          {
              Id = ormUser.Id,
              Name = ormUser.Name,
              IsUserAdmin = IsUserAdmin(ormUser.Permissions)
          }
      }
  
      private bool IsUserAdmin(IList&lt;Permission&gt; permissions)
      {
          return permissions.SomeLinq(ToFindIfTheyAreAnAdmin);
      }
  }
  </code></pre>
  
  <p>This is a simple example but shows how a data model, contains a lot of the same sort of information, but at this view in question you do not care about all the information just a subset of it. This way having a mapper you get to abstract not only the mapping but the communication with the data domain, however you need to write a mapper class for each type, and the above assumes it is a one way mapping, not a 2 way mapping which would require some more code.</p>
  
  <p>So how do you all go about carrying out this mapping? As currently I have just been writing abstraction mappers which basically allow the UI layer to run a query, and get back a view model, abstracting the repositories and the copying data from one model to another, and it just feels like there should be a better way to do this.</p>