title: How to deep clone objects containing an IList property using AutoMapper
body: <p>I am trying to deep clone the following class using AutoMapper:</p>
  
  <pre><code>public class MainData
  {
      public MainData()
      {
          Details = new List&lt;Detail&gt;();
      }
  
      public int Id { get; private set; }
      public DateTime LastUpdate { get; private set; }
      public IList&lt;Detail&gt; Details { get; private set; }
      public int Prop1 { get; set; }
      public int Prop2 { get; set; }
  
      public void AddDetail(Detail detail)
      {
          Details.Add(detail);
      }
  
      public void RemoveDetail(Detail detail)
      {
          Details.Remove(detail);
      }
  
      public MainData Clone()
      {
          Mapper.Reset();
          Mapper.CreateMap&lt;MainData, MainData&gt;().ForMember(d =&gt; d.Id, o =&gt; o.Ignore());
          // Mapper.CreateMap&lt;Detail, Detail&gt;().ForMember(d =&gt; d.Id, o =&gt; o.Ignore()); // REMOVED
          var newMainData = new MainData();
          Mapper.Map(this, newMainData);
          newMainData.Details = this.Details.Select(item =&gt; item.Clone()).ToList(); // ADDED
          return newMainData;
      }
  }
  
  public class Detail
  {
      public int Id { get; private set; }
      public string Name { get; set; }
      public double Area { get; set; }
      public double Height { get; set; }
  
      public Detail Clone() // ADDED
      {
          Mapper.CreateMap&lt;Detail, Detail&gt;().ForMember(d =&gt; d.Id, o =&gt; o.Ignore());
          var newDetail = new Detail();
          Mapper.Map(this, newDetail);
          return newDetail;
      }
  }
  </code></pre>
  
  <p>The <code>Clone</code> method works fine for the MainData properties but seems to only do a shallow copy of the Details list. I have tried adding <code>.ForMember(d =&gt; d.Details, o =&gt; o.UseDestinationValue())</code> but this does not copy the Details list at all. How can I get the Details list deep cloned as well ie, so I end up with two totally independent objects including all the list items?</p>
  
  <p><strong>UPDATE:</strong> I need to exclude the Id property as I am using these objects with NHibernate so not sure if the Serializable solution will do this.</p>
  
  <p><strong>UPDATE2:</strong> Modified the above code to clone the IList too. This seems to work fine as I can exclude properties that make NHibernate think it has already been saved.</p>