Good morning, I am trying to append a TClientDataSet with another, but it may be that these 2 datasets have the same records. The problem is that this generates a Key violation error when trying to append, but I need to have the 2 records even if they are duplicates. I would like to add a field to the dataset and indicate that it is part of the Primary key, but I don't know how to do it.
This is the code I use to create the TClientDataSet:
//Esta funcion recibe como parametro ,la query y un boolean, y devuelve un TClientDataSet
function fxQueryToCDS(pqQuery : TFXQuery; pbFreeQuery : Boolean = true) : TClientDataSet;
var
dspCDS : TDataSetProvider;
begin
dspCDS := TDataSetProvider.Create(nil);
Result := TClientDataSet.Create(nil);
dspCDS.DataSet := pqQuery;
try
Result.Data := dspCDS.data;
finally
FreeAndNil(dspCDS);
if pbFreeQuery then
FreeAndNil(pqQuery);
end;
Result.Open;
end;
This is a part of the code, it is in which it gives me the Key violation:
cdsConsulta1Principal := fxQueryToCDS(query1);
cdsConsulta1Sucursal := fxQueryToCDS(query2);
cdsConsulta1Principal.AppendData(cdsConsulta1Sucursal.Data, False);//aca da key violation si hay registros iguales.
cdsConsulta1Principal.MergeChangeLog;
Yes or if I need to append the records, even if they are duplicates, because the data comes from 2 different databases, but I can't think of how.
The ClientDataSet relies on the information provided by the fields of the underlying dataset to determine the key of the ClientDataSet. Adding a new field, because of the way you're mapping the data, can be a bit more complicated.
My first suggestion, since you want to allow duplicates, is that you could leave the receiving ClientDataSet without a key. You would still be able to push changes back to a database using field values or defining a new key later.
In order to leave the ClientDataSet without any keys, assuming that your queries have persistent fields, at design time or before opening the query, take the key fields of the query and make sure that its property
ProviderFlags
does not include the flag[pfInKey]
, for example:If you don't know what the key fields are or you want to treat it in a generic way, you can go through all the fields of the query: