How to get matching records from Duplicate Rule failure in Salesforce using Apex?

How to get matching records from Duplicate Rule failure in Salesforce using Apex?

Sample Code:


        Contact contact = new Contact(LastName = ‘Test’);
        Set < Id > duplicateIds = new Set < Id >();
Database.SaveResult saveResult = Database.insert(contact, false);


        if ( !saveResult.isSuccess() ) {
            for ( Database.Error err : saveResult.getErrors() ) {
                if ( err instanceof Database.DuplicateError ) {
                    Database.DuplicateError duplicateError = (Database.DuplicateError)err;
                    Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();
                    Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();
                    Datacloud.MatchResult matchResult = matchResults[0];
                    Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
                    for ( Datacloud.MatchRecord matchRecord : matchRecords ) 
                        duplicateIds.add(matchRecord.getRecord().Id);
                }
            }
        }

Reference Link – https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_Datacloud_DuplicateResult.htm

Leave a Reply