Cloning entities as new

Posts   
 
    
aaswin
User
Posts: 4
Joined: 21-Sep-2013
# Posted on: 24-Oct-2013 03:26:29   

Suppose I have an entity called class and each class has students

Like this:

Class | -_______Student

How can I clone the entity class and its students?

Is the following code sufficient?


classEntity.IsNew = true;
classEntity.IsDirty = true;

foreach(var student in classEntity.Students)
{
      student.IsNew = true;
      student.IsDirty = true;
}

uow.Save();

I believe something like this will work with EF, but I'm not clear about LLBLGen, if the framework will traverse the object graph and update the references. ie. the new students, should now be pointing to the newly created classEntity.

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 24-Oct-2013 08:08:46   

That codes seems ok. However it has the problem you mention (the references). Also, what has been changed in the cloned entity? that is not clear, so you have to mark all fields as changed as well.

This is a very useful general-purpose entity cloner by Matthew M.: http://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=7568&StartAtMessage=0&#41748

And you can use it this way:

// load some graph
PrefetchPath path = new PrefetchPath((int)EntityType.CustomerEntity);
path.Add(CustomerEntity.PrefetchPathOrders);
CustomerEntity customer = new CustomerEntity("ALFKI", path);

// create a cloned graph
CustomerEntity newCustomer = (CustomerEntity) xyz.CloneHelper.CloneEntity(customer);

// this is my new customer
newCustomer.CustomerId = "YUJU";

// save the whole graph
newCustomer.Save(true);
David Elizondo | LLBLGen Support Team