Problem copying entities from one DB to another

Hi + tx for any info.

I want to copy data from an MSSQL database to an SQLite database.

This is how I create the object managers:

function TmodelMain.CreateMSSQLManager: TObjectManager;
begin
  Result := TObjectManager.Create(conMSSQL.CreateConnection, TMappingExplorer.Get('Source'));
end;

function TmodelMain.CreateSQLiteManager: TObjectManager;
begin
  Result := TObjectManager.Create(conSQLite.CreateConnection, TMappingExplorer.Get('Target'));
end;

This is how I copy the data:

 for LebensmittelMSSQL in modelMain.GetLMCursor(nTotal) do begin
    modelMain.AddLebensmittelToSQLite(LebensmittelMSSQL);
  end;

Finally, the saving:

procedure TmodelMain.AddLebensmittelToSQLite(Lebensmittel: entityLebensmittel.TTBLLebensmittel);
begin
  mgrSQLite.Save(Lebensmittel);
end;

However, on destroying things,

procedure TmodelMain.DataModuleDestroy(Sender: TObject);
begin
  FreeAndNil(mgrMSSQL);
  FreeAndNil(mgrSQLite);
end;

freeing the mgrSQLite fails with an invalid pointer.

If I comment the line mgrSQLite.Save, freeing the managers succeeds. I think,the entity belongs now to both managers and this is why the second free fails, as it also tries to free the entity.

What am I doing wrong here?

Thanks for support!

Reread the docs. :- )

If I understand things right, the problem is, that both managers own the entity. So setting the OwnsObjects to false for one of the managers should solve the situation.

Is this correct?

Yes, that is correct.
Alternatively, instead of Save you can use Replicate method, which will create a copy of the object in the other manager.

Replicate is slower but better suited to migrate data, since it will not only create a new record if it doesn't exist, but also update existing records with the new data. It will also replicate all associated objects.

Thank you, Wagner, for the answer and the explanation.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.