Search code examples
salesforceupsertsalesforce-lightningrest

Salesforce Bulk Upsert throws Duplicate error


I am doing the R&D on the duplicate error scenario in SF Bulk API and found that somehow I am not able to perform insert and update operation simultaneously for the contact with the same(external id) within the single batch.

I received a duplicate error. Screen capture for reference

https://www.screencast.com/t/ReE41vuzb

When the batch contains different external id's I do not have any error. But when external Id is repeated in a single batch I receive the below error. { "success" : false, "created" : false, "id" : null, "errors" : [ { "message" : "Duplicate external id specified: 7401", "fields" : [ "Origami_ID__c" ], "statusCode" : "DUPLICATE_VALUE", "extendedErrorDetails" : null }

Although there is No duplicate at the target side.


Solution

  • You just need the last record from multiple records with same unique id.

    For this follow the below logic:

    //Create Map and populate the map with last record having unique id
    Map<String,MyObject__c> mapWithUniqueIdMyObject = new Map<String,MyObject__c>();
    MyObject__c currentObject;
    for(Integer currentPosition = myObjectListWith5000Records.size(); currentPosition >=0 ;currentPosition--){
         currentObject = myObjectListWith5000Records.get( currentPosition );
         if( !mapWithUniqueIdMyObject.containsKey(currentObject.Origami_ID__c) ){//If the map does not contain any object with unique id then put the object in the map
              mapWithUniqueIdMyObject.put( currentObject.Origami_ID__c, currentObject );
         }
    } 
    upsert mapWithUniqueIdMyObject.getValues();