Lee Fang
Lee Fang

Reputation: 51

Salesforce apex trigger duplicate id in list

In my order insert trigger, i need to update contact for the order information, I know there are duplicate records in the my contact list. so I use Contact[] contactToUpdate = new List(new Set(contactList)); to remove the duplicates.

but I still receive the error message: duplicate in List.

any idea??

Thanks

Upvotes: 3

Views: 7048

Answers (1)

Matt Lacey
Matt Lacey

Reputation: 8255

Your are correct that a set contains unique elements, but the issue is that you're dealing with instances of contact: just because two instances refer to the same contact in the DB they are still different object instances in memory and therefore are unique, the upshot being you can have to entries in the set representing the same contact with the same id.

The easiest way around this would be to use a map of id to contact:

map<Id, Contact> contactMap = new map<id, Contact>();

For each order you process, you can use the contact lookup as a key to the map to reach the contact you want to update. At the end of your processing you can then update the contacts simply by calling:

update mapContacts.values(); 

Upvotes: 6

Related Questions