function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
tcsellstcsells 

Duplicate IDs in DML list

I have a trigger that updates records in a list.  The list will potentially have duplicates and will cause the DML operation to fail with the “System.ListException: Duplicate id in list” error.  I thought I could solve it by populating a set, then converting the set to a list (see code), but that didn’t work either.

 

        if (!commitupdates.IsEmpty()){
List<WV_Commitments__c> commitupdatelist = new list<WV_Commitments__c>(); commitupdatelist.addall(commitupdates); update commitupdatelist; }

 

 

Is there a reliable way to ensure that no duplicate objects are added to a list or set for a DML operation?  Thanks in advance for any suggestions.

 

Todd

JFraileJFraile

Hi.

I had the same the problem and using a set worked for me. This is my code:

if(FactsExito.size()>0)	
        Set<Factura__c> myset = new Set<Factura__c>();
	List<Factura__c> result = new List<Factura__c>();
	myset.addAll(FactsExito);//deletes duplicates
	result.addAll(myset);//populates new list without duplicates           
        update result;

 Let me know if that worked

Hengky IlawanHengky Ilawan

Hi Todd,

 

Another way to populate your list is to put them into a map, and then get the list by calling the values() method. That will ensure you won't have a duplicate IDs.

 

-Hengky-

tcsellstcsells

Thanks for the solutions.  I discovered that my problem was that even though the object ID was a duplicate, the actual object was not because it had different data in the fields.

 

My solution was to track the IDs in a set, and only add the object if I successfully added the ID to the set.  I don’t know if this is the best practice, but it works.

 

set<id> idstoupdate = new set<id>();
List<WV_Commitments__c> commitupdates = new List<WV_Commitments__c>();

...

if (idsToUpdate.add(TargetCommitment.ID)) commitupdates.add(TargetCommitment);

 Thanks again for the feedback.

 

-Todd