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
Anusha GowravarapuAnusha Gowravarapu 

upsert failed in colleborationgroup member object

Hi, I am trying to upsert members to collaboration chatter group but I am receving 
"common.apex.runtime.impl.DmlExecutionException: Upsert failed. First exception on row 0; first error: DUPLICATE_VALUE, User is already a Member of this group" exception.
Can some one suggest how to avoid this.Below is my code
List<DistributionList__c> userID=[SELECT userID__C FROM DistributionList__c where ChatterGroupName__c='testgroup'];
        List<CollaborationGroupMember> CollGroupMembers = new List<CollaborationGroupMember>();
        for(DistributionList__c user : userID)
        {
       
        CollaborationGroupMember member = new CollaborationGroupMember();
        member.MemberId = user.userID__C;
        member.CollaborationGroupId = '0F94D0000004Ebd';
        CollGroupMembers.add(member);
        
        }
        
        try
        {
        
        upsert CollGroupMembers;
        
        }
        catch(DMLException e)
        {
        
        system.debug('The group members werent added properly.  Error: '+ e);
        
        }       
Fabio FabianoFabio Fabiano
Does the DistributionList__c contains the Owner of the Group?
Anusha GowravarapuAnusha Gowravarapu
Yes it is
Fabio FabianoFabio Fabiano
Good, so you need to remove the Owner from that list since the owner is already a member.
Anusha GowravarapuAnusha Gowravarapu
Thanks Fabio..! I am thinking to do this way, If group.memberId=distributionlist.userId then skip insert other wise proceed for insert. Appreciate your time.