[SalesForce] System.ListException: Before Insert or Upsert list must not have two identically equal elements

I am trying to upsert some CustomObject__c record based on some criteria related to Opportunity Records.

Set<Property2__c> properties = new Set<Property2__c>();
 List<Property2__c> upsertProperties = new List<Property2__c>();
for (Opportunity opp : opps) {
        Property2__c prop = new Property2__c();
        String propCheck = opp.Street_opp__c + '---' + opp.Postal_Code_ZIP_opp__c;
        if (szToProperty.containsKey(propCheck)) {
            prop = szToProperty.get(propCheck); // check for property
            properties.add(prop);
        }
        else{
            if (!properties.contains(prop)) properties.add(prop);
            prop.Name = opp.Street_opp__c;
            prop.Account__c = opp.AccountId;
            prop.Street__c = opp.Street_opp__c;
        }
       if (!properties.contains(prop)) { 
                properties.add(prop);
            } // ensure we don't update twice. -- upsertProperties.add(prop);
        }
}
if (properties.size() > 0) {
  upsertProperties.addAll(properties);
  System.debug('\n\n---Upsert Size---: ' +upsertProperties.size());
  upsert upsertProperties;
}

But I am getting some Exception –

System.ListException: Before Insert or Upsert list must not have two
identically equal elements

I am checking for the Duplicate Record in this code but still getting this exception. Any Help??

Best Answer

I think i found the solution, Actually the above code is working fine as i swaped some lines in Original code(which was causing problem).

Original code :

Set<Property2__c> properties = new Set<Property2__c>();
List<Property2__c> upsertProperties = new List<Property2__c>();
for (Opportunity opp : opps) {
    Property2__c prop = new Property2__c();
    String propCheck = opp.Street_opp__c + '---' + opp.Postal_Code_ZIP_opp__c;
    if (szToProperty.containsKey(propCheck)) prop = szToProperty.get(propCheck); // check for property
    else szToProperty.put(propCheck,prop); // new property; add to the map in case multiple opps with existing records 
    System.debug('\n\n----Before adding --- : ' + prop);
    if (!properties.contains(prop)) { 
        properties.add(prop);
        prop.Name = opp.Street_opp__c;
        prop.Account__c = opp.AccountId;
        prop.Street__c = opp.Street_opp__c;
    }
}

if (properties.size() > 0) {
  upsertProperties.addAll(properties);
  System.debug('\n\n---Upsert Size---: ' +upsertProperties.size());
  upsert upsertProperties;
}

But it gave me error

System.ListException: Before Insert or Upsert list must not have two identically equal elements

Reason : The code checks for the set.contains When the fields are not initialised, hence there is a risk of adding duplicate record

if (!properties.contains(prop))

I have done some reordering in the code(included in the Question itself) and it worked for me.

Thanks for the help guys:)

Related Topic