I want to transfer the contacts from account AA to account BB without duplicates.
If Account AA have Dup2,Dup3,Dup4,Dup2,Dup3,Dup4,Dup2,Dup3 and Dup4 contacts, for the first time We need to transfer Dup2,Dup3 and Dup4 to Account BB. If we run second time, it should not transfer duplicate records again and keeping them in same account AA.
Public class Example11 {
Public List<Account> accs;
Public List<Account> aacc;
Public List<Contact> conupdate;
Public Set<Contact> setUpdate;
Public Set<String> setresult;
Public List<Id> conids;
Public void main(){
setresult = new Set<String>();
conIds = new List<Id>();
setUpdate = new Set<Contact>();
accs = [select id,name,(select id,lastname,AccountId from contacts) from Account where id='0012800001EcUSl'];
for(Account aa : accs) {
for(Contact cc: aa.contacts) {
if(setresult.contains(cc.lastname)){
//conids.add(cc.id);
}
else{
conids.add(cc.id);
setresult.add(cc.lastname);
}
}
}
List<Contact> consd=[SELECT id,lastname,AccountId FROM Contact WHERE Id=: conids];
aacc = [select id,name,(select id,lastname,AccountId from contacts) from Account where id='0012800001EcUSj'];
for(Account aa : aacc) {
for(Contact conc: aa.contacts) {
for(Contact cca : consd) {
if(conc.lastname != cca.lastname){
cca.AccountId = '0012800001EcUSj';
setUpdate.add(cca);
}
}
}
}
conUpdate = new List<Contact>(setUpdate);
update conUpdate;
}
}
I tried with above class. For the first time, i can able to send Dup2,Dup3 and Dup4 to Account BB with out duplicates.
But the first issue is, while i am checking second time, duplicates contacts are saving to Account BB.
Second issue is, Contact records can able to transfer if account BB have atleast one contact. If account BB does not have any contacts, Dup2,Dup3 and Dup4 are not transferring.
I tried with lot of efforts without success. But i couldn't succeed it.