Print Page | Close Window

Deep copy an entity tree

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2010
Forum Discription: For .NET 4.0
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=2089
Printed Date: 10-Jun-2026 at 6:55pm


Topic: Deep copy an entity tree
Posted By: bigme
Subject: Deep copy an entity tree
Date Posted: 24-Aug-2010 at 4:44pm
I have an existing Order and a collection of OrderDetails that I need to duplicate as the basis for a new order. At the moment I simply create new entities and copy the properties I want. Is there a less brittle, more DevForce-oriented way to do this?

Dave.




Replies:
Posted By: bigme
Date Posted: 25-Aug-2010 at 3:29pm
The Order and OrderDetails are, of course, standard IdeaBlade-generated objects and collections, a la Northwind.

Dave.


Posted By: ting
Date Posted: 25-Aug-2010 at 7:43pm
You can clone an entity by explicitly casting to IClonable and calling Clone().  This will return you a detatched entity with all of the fields copied.  You should now call EntityManager.GenerateID() to assign it a new primary key and add it to the EntityManager.  Make sure to assign the primary key before adding it to the EntityManager.
 
Here's an example:
Employee newEmployee = (Employee) ((ICloneable)employee).Clone();
mgr.GenerateId(newEmployee, Employee.PropertyMetadata.EmployeeID);
mgr.AddEntity(newEmployee);
 


Posted By: bigme
Date Posted: 25-Aug-2010 at 9:20pm
Thanks Ting,

 If I do as you say above then I get a new order (without OrderDetails), but the original order has its PK changed to the same value as the newly added order !!

So it seemed that I should NOT explicitly add the cloned Order to the mgr.Orders collection, but just rely on the cloning of the Customer navigation property? When I do this I don't get a new Order, but it still changes the PK of the current order (the one being cloned)

I suspect this is related to the fact that I am working with a collection of customer.Orders and not mgr.Orders??

Dave.


Posted By: ting
Date Posted: 26-Aug-2010 at 4:28pm

My bad.  I should have tested this first.  ICloneable.Clone does not have the correct implemenation.  I have an architect looking at this.



Posted By: ting
Date Posted: 31-Aug-2010 at 1:37pm
Clone will be fixed for the release this week.  Sorry for the false start!



Print Page | Close Window