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
NeeloferNeelofer 

how to perform upsert operation on opportunity contact role

In OpportunityContactRole there is no externalid field and we can't create custom filed..when I try to parse json data for every opportunity we got two similar contact role records means duplicate records..how can we avoid this...
Abdul KhatriAbdul Khatri
Can you provide the sample json?
Abdul KhatriAbdul Khatri
Well you haven't provide any details but I think you can create a method with the parameter List<OpportunityContactRole> to be passed that you deserialized from the JSON. Here is the code.
 
public void upsertOpportunityContactRole (List<OpportunityContactRole> oppContactRoleList)
{
	List<Id> idOppList = new List<Id>();
	Map<Id, Set<String>> idOppRoleMap = new Map<Id, Set<String>>();
	List<OpportunityContactRole> oppContactRoleToInsertList = new List<OpportunityContactRole>();
    
    for(OpportunityContactRole contactRole : oppContactRoleList) {
        idOppList.add(contactRole.OpportunityId);
    }

    List<Opportunity> oppList = [Select Id, (Select OpportunityId, ContactId, Role From OpportunityContactRoles) From Opportunity Where Id IN :idOppList];
    
    for(Opportunity opp : oppList) {
        
        if(opp.OpportunityContactRoles == null) continue;
        
        for(OpportunityContactRole contactRole : opp.OpportunityContactRoles) {
            
            if(idOppRoleMap.contains(opp.Id)) {               
                Set<String> roleSet = idOppRoleMap.get(opp.Id);
                roleSet.add(contactRole.Role);
                idOppRoleMap.put(opp.Id, roleSet);
            }else{
                idOppRoleMap.put(opp.Id, new Set<String>{roleList});
            }
        }
    }
    
    for(OpportunityContactRole contactRole : oppContactRoleList) {
        
        if(idOppRoleMap.get(contactRole.OpportunityId).Contains(contactRole.Role)) continue;
        
        OpportunityContactRole oppContactRoleToInsert = new OpportunityContactRole();
        oppContactRoleToInsert.OpportunityId = contactRole.OpportunityId;
        oppContactRoleToInsert.Role = contactRole.Role;
        
        oppContactRoleToInsertList.add(oppContactRoleToInsert);
    }
    
    if(oppContactRoleToInsertList.size() > 0)
        insert oppContactRoleToInsertList;
    
}