I am trying to run the following piece of code to update all Accounts without a primary contact. This method will look through all contacts of an account and assign the first contact it reads to be the primary contact of the account.
I am running into a System.LimitException: Too Many DML Statements: 151 error for exceeding 151 DML operations. Does anybody have any suggestions as to how I can resolve this?
public class setPrimaryContact {
public static void setPrimary(){
boolean assigned = false;
List<Account> accountList = [
SELECT Name, Primary_Contact__c, (select id, Lastname, Type__C from contacts)
FROM Account
];
//Loop through all accounts
for(Account acc:accountList){
assigned = false;
//Check if the account has contacts
if(acc.Contacts.size()>0){
//Check if the account already has a primary contact
if(acc.Primary_Contact__c == null){
//Loop through each contact
for(Contact c:acc.Contacts){
//Check to see if the contact is a primary contact
if(!assigned && (c.Type__c == 'Primary Contact')){
//Assign that primary contact to be the Primary_Contact__c of the account
acc.Primary_Contact__c = c.Id;
assigned = true;
update acc;
}
}
} else {
System.debug(acc.Name+' already has a primary contact .');
}
if(!assigned){
System.debug(acc.Name+' has no primary contacts.');
}
} else {
System.debug(acc.Name+' has no contacts.');
}
}
}
}