Clone with many branches - Changing the PK

Posts   
 
    
ianvink
User
Posts: 394
Joined: 15-Dec-2006
# Posted on: 10-Jul-2007 20:48:07   

I have an object with many children, grand children etc.... Big and bushy branches.

Let's call it a **SaleEntity **and it is loaded from the DB. It's not new.

I use this to clone it nicely.

        
public static T CloneEntity<T>(T obj) where T : class, ISerializable
{
     using (MemoryStream buffer = new MemoryStream())
     {
        BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
        formatter.Serialize(buffer, obj);
        buffer.Position = 0;
        return (T)formatter.Deserialize(buffer);
     }
}

I need to increment the SaleEntity's PK, SaleEntity.SalePK, by 1 then go to each child collection and update their PK by one and so one down the chain. Then save the SaleEntity back to the DB.

Of course when I increment the SaleEntity.SalePK I loose all its child Collections.

Is there a way to change a PK and have that change flow down to all the children on an object that has been loaded from the DB?

Thanks, Ian

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 11-Jul-2007 09:59:37   

Is there a way to change a PK and have that change flow down to all the children on an object that has been loaded from the DB?

Try creating a new SaleEntity with the new PK, and add to it all the related entities/collections of the old entity. This way the old entity will be de-referenced from all the related entities and the new one will be referenced instead.