How do you deep clone a persistent entity in ColdF

2019-07-01 22:51发布

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?

2条回答
放荡不羁爱自由
2楼-- · 2019-07-01 23:10

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.

查看更多
再贱就再见
3楼-- · 2019-07-01 23:12

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.

查看更多
登录 后发表回答