title: Copy Entity Framework Object
body: <p>I have a EF4.1 class X and I want to make copy of that plus all its child records.
  X.Y and X.Y.Z</p>
  
  <p>Now if I do the following it returns error.</p>
  
  <p>The property 'X.ID' is part of the object's key information and cannot be modified.</p>
  
  <pre><code>public void CopyX(long ID)
  {
      var c = db.Xs.Include("Y").Include("W").Include("Y.Z").SingleOrDefault(x =&gt; x.ID == ID);
      if (c != null)
      {
          c.ID = 0;
          c.Title = "Copy Of " + c.Title;
          for (var m = 0; m &lt; c.Ys.Count; m++)
          {
              c.Ys[m].ID = 0;
              c.Ys[m].XID=0-m;
              for (var p = 0; p &lt; c.Ys[m].Zs.Count; p++)
              {
                  c.Ys[m].Zs[p].XID = 0 - m;
                  c.Ys[m].Zs[p].ID = 0 - p;
              }
          }
          for (var i = 0; i &lt; c.Ws.Count; i++)
          {
              c.Ws[i].ID = 0 - i;
              c.Ws[i].XID = 0;
          }
          db.Entry&lt;Content&gt;(c).State = System.Data.EntityState.Added;
          db.SaveChanges();
      }
  }
  </code></pre>
  
  <p>Or Is there other way of making copy of entity objects. </p>
  
  <p>NOTE: there are multiple properties in each W,X,Y,Z.</p>