Duplicate a TEntity

I want to generate a new record on a database duplicating an existing record. what's wrong with my code bellow?

FMaterialOrigem := THelperConnection.GetManager(CNREPEATABLEREAD).Find
.Where(Linq['CODIGOMATERIAL'] = FNivel)

vManagerLocal := TObjectManager.Create(THelperConnection.SnapshotConnectionPool.GetConnection);

vCadMaterial := vManagerLocal.Find.Where

vCadMaterial.CODIGOMATERIAL := FProximoCodigo;
vCadMaterial.NIVEL := '9';
vCadMaterial.CODIGOAUXILIAR := FCodigoAuxiliar;
vCadMaterial.CODIGOTABELAPRECOITEM := FProximoCodigo;
vCadMaterial.DESCRICAO := pDescricao;
vCadMaterial.STATUS := pStatus;
vCadMaterial.UNIDADESAIDA := FMaterialOrigem.UNIDADESAIDA;
if pCodigoClasse <> '' then
  vCadMaterial.CODIGOCLASSTERAPEUTICA := pCodigoClasse;
if pApresentacao <> '' then
  vCadMaterial.APRESENTACAO := pApresentacao;
vCadMaterial.CODIGOGENERO := vManagerLocal.Find<TCADGENEROMATERIALSERVICO>(Copy(NCM, 1, 2)) ;
vCadMaterial.OBSERVACAO.AsUnicodeString := RetornaObservacaoMat(pNumeroOrdemProduto, pCodigoAuxiliar, pNumeroNF, pNomeFor, pValorProduto);
if pCodigoAuxiliar = '' then
  vCadMaterial.CODIGOAUXILIAR := pCodigoAuxiliar;
vCadMaterial.IDMATERIAL := 0; //My ID Property

Result := vCadMaterial;

Error Message: First chance exception at $00007FFB43DE4ED9. Exception class EAssertionFailed with message 'Assertion failure (C:\Users\Desenvolvedor\Documents\tmssoftware\TMS Aurelius\source\core\Aurelius.Engine.ObjectMap.pas, line 380)'. Process InformServerXD.exe (2736)

Since you have previously loaded the vCadMaterial from the target manager:

vCadMaterial := vManagerLocal.Find.Where

You shouldn't use neither Replicate nor Save. Just call Flush to update the object properties:


Use Flush to update changes in an object that is already loaded in the manager.
Use Replicate to create a copy (replica) of an object that is not loaded in the manager.
Use Save to create a new object (insert) of an object that is not loaded in the manager but will then be added to it after Save is performed.

Hi Wagner, i think that i didn't explain correct, i need to create a new object that's a copy of the first one, changing some atributes and saving the second one after do these changes and with a new ID.
Object1.ID recorded in Database = 72;
NewObject a Copy of Object1 but with a new ID.

Clear the id (set to zero) and use Replicate to create a clone of the original object.

I see, first i need to replicate, only then I can change de atributes and save. Thanks for the answer.

Not necessarily, you can modify the properties before replicating (that would of course modify the original object).