You need to sign in to do that
Don't have an account?
Duplicate Id in list Batch Apex
Hi Folks,
I do receive "Duplicate Id in List" error when I run the code. Please could you revew and advise what is wrong and what can be improved here ? Duplicate Id was found in list "acctaddresstoupdate ". Many Thanks in advance.
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator([Select id, BDF_Target__c, OCE__PreferredAddress__c, OCE__PreferredAddress__r.BDF_Visited__c from OCE__AccountTerritoryFields__c where OCE__PreferredAddress__c != null]);
}
global void execute(Database.BatchableContext BC, List<OCE__AccountTerritoryFields__c> scope) { system.debug(scope);
list<OCE__AccountAddress__c> acctaddresstoupdate = new list<OCE__AccountAddress__c> ();
map<id,OCE__AccountAddress__c> Acctaddnodupes = new map <id,OCE__AccountAddress__c>();
for(OCE__AccountTerritoryFields__c acctterfields : [Select id, BDF_Target__c, OCE__PreferredAddress__c, OCE__PreferredAddress__r.BDF_Visited__c from OCE__AccountTerritoryFields__c where id IN :scope]) {
system.debug(acctterfields);
acctaddresstoupdate.add(acctterfields.OCE__PreferredAddress__r);
if(acctterfields.BDF_Target__c == 'Yes') {
system.debug('Completed');
acctterfields.OCE__PreferredAddress__r.BDF_Visited__c = true;
update acctaddresstoupdate;
system.debug(acctaddresstoupdate);
}
else {
system.debug('Not Completed');
acctterfields.OCE__PreferredAddress__r.BDF_Visited__c = false;
update acctaddresstoupdate;
system.debug(acctaddresstoupdate);
}
}
map<id,OCE__AccountAddress__c> AcctAddmap = new map <id,OCE__AccountAddress__c>();
AcctAddmap.putAll(acctaddresstoupdate);
if(AcctAddmap.size()>0){
update AcctAddmap.values();
}
}
Resolution:
- Create a map of <id,sobject>
- Convert the list to Map so that the duplicate IDs are removed.
- Update or Delete the values part of the Map.
Sample CodeSee Error 'System.ListException: Duplicate id in list' in Apex to learn more
Let me know if this helps, if it does, please mark this answer as best so that others facing the same issue will find this information useful. Thank you
You can then do the insert / update as required.
regards
Andrew