title: Generic deep cloning with depth limitation in tree hierarchy
body: <p>I'm using Code First development with Entity Framework. The problem is:
  while cloning lazy loaded list, list elements are type of:</p>
  
  <p><code>System.Data.Entity.DynamicProxies.Node_CB2936E7A8389F56009639CD3D732E4B509C4467531A6AFB3A143429D77A07DF</code> </p>
  
  <p>and my generic function see it as <code>System.Object</code>. Is there any way to cast this object to they parent class, before they are pass to <code>Clone</code> function? Or other ideas?</p>
  
  <p>Because  I need clone only to specific depth, I can't serialize whole tree structure and then deserialize it.</p>
  
  <p>My model is: </p>
  
  <pre><code>public class Node
  {
      public int Id { get; set; }
  
      public String Name { get; set; } 
  
      public virtual IList&lt;Node&gt; Nodes { get; set; } 
  
      public int? ParentId { get; set; }
  
      [ForeignKey("ParentId")]
      public virtual Node Parent { get; set; }
  }
  </code></pre>
  
  <p>And function use to clone:</p>
  
  <pre><code>protected T Clone&lt;T&gt;(T entity, int depth) where T : new()
  {
      var cloned = new T();
      foreach (var property in cloned.GetType().GetProperties())
      {
          if (property.PropertyType.Namespace == "System" &amp;&amp; property.CanWrite)
          {
              property.SetValue(cloned, property.GetValue(entity));
          }
          else if (depth &gt; 0 &amp;&amp; property.CanWrite)
          {
              if (property.PropertyType.Namespace == "System.Collections.Generic")
              {
                  var type = property.PropertyType.GetGenericArguments()[0];
                  Type genericListType = typeof(List&lt;&gt;).MakeGenericType(type);
                  var collection = (IList)Activator.CreateInstance(genericListType);
                  var value = property.GetValue(entity);
                  foreach (var element in value as IEnumerable)
                  {
                      collection.Add(Clone(element, depth - 1));  // here is Error:
                          //The value “System.Object” is not of type “Sandbox.Models.Node” and cannot be used in this generic collection. Parameter name: value
                          //I should cast element to its parent class but how?
                  }
                  property.SetValue(cloned, collection);
              }
          }
      }
      return cloned;
  }
  </code></pre>
  
  <p>This function works perfect on non-Entity Framework objects.
  And usage of <code>Clone</code> function is:</p>
  
  <pre><code>var cloned = Clone(context.Nodes.Find(10), 2);
  </code></pre>
  
  <p>Any help would be appreciated.</p>