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
Now if I do the following it returns error.
The property 'X.ID' is part of the object's key information and cannot be modified.
public void CopyX(long ID)
{
var c = db.Xs.Include("Y").Include("W").Include("Y.Z").SingleOrDefault(x => x.ID == ID);
if (c != null)
{
c.ID = 0;
c.Title = "Copy Of " + c.Title;
for (var m = 0; m < c.Ys.Count; m++)
{
c.Ys[m].ID = 0;
c.Ys[m].XID=0-m;
for (var p = 0; p < 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 < c.Ws.Count; i++)
{
c.Ws[i].ID = 0 - i;
c.Ws[i].XID = 0;
}
db.Entry<Content>(c).State = System.Data.EntityState.Added;
db.SaveChanges();
}
}
Or Is there other way of making copy of entity objects.
NOTE: there are multiple properties in each W,X,Y,Z.
.Include("Y")and.Include("Y.Z"). The secondIncludewill include both Y and Z - it has to, if you think about it.