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
Harsha ShriHarsha Shri 

Prevent duplicate records using apex program not trigger

Hi All,
I want to prevent duplicate records while saving. I do not want to create trigger for this. I want to do it in apex class. Here is my requirement.
I have two object. one is bank__c and another one is customer__c. both are having master detail. master is bank__c and child is customer__c.
Right now I am saving records as below.
cus.add(new customer__c(bank__c=bankId,accountnum__c=data.num__c));

here data variable is wrapper list that I am assigning to accountnum__c.
I want to prevent duplicate records with duplicate num__c. I dont want to create trigger for this. I want to do changes only apex class.
Please suggest me how to do this.
Please help me.
Thanks in Advance
Best Answer chosen by Harsha Shri
jigarshahjigarshah
Harsha,

I believe you intend to capture and avoid adding duplicate Customer records whenever they are added. Moreover, you intend to do so without writing an Apex trigger for performing dupe checks.
  • Create a new Text field on Customer and call it CustomerDupeKey__c. Mark this field as Unique.
  • The CustomerDupeKey__c field is a combination of BankId and CustomerCode separated by an underscore "_".
  • In your Apex code, you generate the CustomerDupeKey__c value and insert the Customer record as usual. If this combination of BankId and CustomerCode already exists, the unique constraint will automatically retrict the creation of a duplicate.
Additionally you can also Duplicate Rules and Matching Rules provided by Salesforce to report or restrict creation of duplicates. This is an out of box feature and requires no Apex code.