How do you deep clone a persistent entity in ColdF

2019-07-01 22:30发布

问题:

I have a persistent entity that I'm using as a template:

Company
    Locations
        Departments
            Employees

In other words, a Company contains many Locations, which contains many Departments, which contains many Employees. I have one Company set up as a template that should be copied when a new company is created. However, this template is persistent in the database. I tried using the following code to deep clone it:

var template = EntityLoadByPK("Company", 13);
var company =  Duplicate(template);
EntitySave(company);

But I receive an error says that the entity is not attached to the session. So then I tried to assign 0 to all the IDs before saving:

company.setId(0);
for (location in company.getLocations())
{
    location.setId(0);
    // more nested for loops
}

But I receive a similar error. Finally, I tried to do a direct 1:1 copy of the properties:

var newCompany = EntityNew("Company");
newCompany.setName(company.getName());
newCompany.setCEO(company.getCEO());
// etc...

But this gets more and more cumbersome the deeper the object graph goes. Is there an easier way of deep cloning a persistent entity so that you get a brand new transient entity, including all of its child collections?

回答1:

last time I encountered the same situation, I just wrote a clone-like method in the root CFC. Cannot call it clone btw, 'cause it's reserved I believe.



回答2:

Have you tried using EntityMerge? You should be able to duplicate an ORM object, NULL out the IDs, and then Merge it back into the session.