title: Entity Framework duplicate object and all child properties
body: <p>Example structure</p>
  
  <pre><code>public class Page
  {
      public int PageId { get; set; }
      public string Prop1 { get; set; }
      public string Prop2 { get; set; }
      public virtual List&lt;Section&gt; Sections { get; set; }
  }
  
  public class Section
  {
      public int SectionId { get; set; }
      public int PageId { get; set; }
      public virtual Page Page { get; set; }
      public virtual List&lt;Heading&gt; Headings { get; set; }
  }
  
  public class Heading
  {
      public int HeadingId { get; set; }
      public int SectionId { get; set; }
      public virtual Section Section { get; set; }
  }
  </code></pre>
  
  <p>It's worth noting that my actual structure has more levels than this but this should be enough to explain what I'm trying to achieve.</p>
  
  <p>So I load my <code>Page</code> object I then Clone that object and make some minor changes to the properties of <code>Page</code> i.e. <code>Prop1</code>, <code>Prop2</code></p>
  
  <pre><code>Page pageFromDb = getPageMethod();
  Page clonedPage = pageFromDb.Clone();
  clonedPage.Prop1 = clonedPage.Prop1 + " Cloned";
  addPageMethod(clonedPage); //Adds the page to db
  </code></pre>
  
  <p>In the example above <code>clonedPage</code> structure is fine and a new <code>Page</code> is added to the database. However I believe because the Id's of the child objects are set and the relationship of the children is always one to many. The original object <code>pageFromDb</code> will lose all it children as entity framework instead of creating new <code>Section</code> objects for the cloned <code>Page</code> will update the <code>Section.PageId</code> to the newly inserted page.</p>
  
  <p>I believe a fix for this would be to <code>foreach</code>, <code>foreach</code>, etc. and set all the Id's to <code>0</code> before inserting then entity framework will create new records foreach object. Is there any easier/better way to clone an object in an entity framework environment.?</p>