0

I need to insert duplicates (the same one field, ID must be different) from SOQL. How can I do this? When I try to insert records with this code:

@isTest(SeeAllData = true) private class PatchPanelTriggerClassTest {

@isTest private static void deleteDuplicatesTest() {
    String patchPanelName = 'hardcoded_data'; 
    patchPanelName = patchPanelName + '%';

    List<Interface__c> records = [SELECT Name, Id, Status__c, Port_No__c, Rack__c, Show_in_Customer_Portal__c FROM Interface__c where Name LIKE :patchPanelName limit 50000];

    insert records;

I get this error message:

Class.PatchPanelTriggerClassTest.deleteDuplicatesTest: line 13, column 1 12:37:48.2 (22988581)|FATAL_ERROR|System.DmlException: Insert failed. First exception on row 0 with id a2m3H0000009UmwQAE; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

2

You would just need to clone them to get rid of the Id

insert records.deepClone();

or if you want to get the Id of those as well...

    List<Interface__c> records = [SELECT Name, Id, Status__c, Port_No__c, Rack__c, Show_in_Customer_Portal__c FROM Interface__c where Name LIKE :patchPanelName limit 10000];
    List<Interface__c> clonedRecords = records.deepClone();

    insert clonedRecords;

Remember that the limit is 10000 for dml rows, so also depending on the triggers behind, you might have to reduce it further

2
  • if you will take limit 50000 in query and insert the list, it will hit the governor limit :-) – Aditya Vijay Jun 12 '20 at 11:02
  • It throws this Exception: System.DmlException: Insert failed. First exception on row 0 with id a2m3H0000009UmwQAE; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] Class.PatchPanelTriggerClassTest.deleteDuplicatesTest: line 15, column 1 (the same Exception like above) – NickName43 Jun 12 '20 at 12:39
1

As Sergio said in his answer, you have to remove the Ids if you want to insert them, but to do that on a List<SObject> you need to call deepClone() instead of clone().

2
  • Code works without exceptions but still there are still no duplicates - as if nothing happened. – NickName43 Jun 12 '20 at 14:20
  • 1
    It is hard to say anything else without seeing more of the test code or understanding where the duplicate deletion itself is supposed to be taking place (some other code block, trigger, etc). Updating the question with those details will make it easier to help. – Stephen SS Jun 12 '20 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.