title: Map a hierarchy object with AutoMapper
body: <p>How can I map a c# class called Unit which has again a <code>List&lt;Unit&gt;</code>.</p>
  
  <p>The concrete scenario is a rootUnit object which contains a List which are the first level children.</p>
  
  <p>The first level children unit objects will not contain any other units so there will be no recursion in the hierarchy.</p>
  
  <pre><code>public class Unit
      {
          public Unit()
          {
              // Explicitly set the default value for the first unit in a hierarchy
              HierarchyIndex = 0;
              Units = new List&lt;Unit&gt;();
          }
  
          public List&lt;Unit&gt; Units { get; set; }
  
          public int UnitId { get; set; }
          public string Name { get; set; }       
          public Nullable&lt;int&gt; ParentId { get; set; }
          public int TemplateId { get; set; }       
          public bool HasChildren { get; set; }
          public bool IsFolder { get; set; }
          public DateTime CreatedAt { get; set; }
          public int HierarchyIndex { get; set; }
      }
  </code></pre>
  
  <p>Map the unit above to this viewmodel:</p>
  
  <pre><code>public class UnitTreeViewModel
  {
      [JsonProperty("key")]
      public int UnitId { get; set; }
      [JsonProperty("title")]
      public string Name { get; set; }
      [JsonProperty("isLazy")]
      public bool HasChildren { get; set; } 
      [JsonProperty("isFolder")]
      public bool IsFolder { get; set; } 
  }
  </code></pre>