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
Tushar AteyTushar Atey 

How write apex code to Insert 5 Accounts and a contact related to each account

HarshHarsh (Salesforce Developers) 
Hi Tushar,
Please try the below code.
list<Account> acclist = new list<Account>();

for(integer i=1; i<5; i++){
    Account objacc = new Account(Name = 'ABC' + i);
    acclist.add(objacc);
}

insert acclist;

list<Contact> conlist = new list<Contact>();

for(Account objacc :acclist){
    Contact objcontact = new Contact();
    objcontact.AccountId = objacc.id;
    objcontact.LastName = objacc.Name;
    conlist.add(objcontact);
}

insert conlist;

Please mark it as Best Answer if the above information was helpful.

Thanks.
 
CharuDuttCharuDutt
Hii Tushar 
Try Below Code
public class AccountRelatedContacts{
    publis static void insertRecords(integer numRec){

list<Account> acclist = new list<Account>();

for(integer i=1; i<=numRec; i++){
    Account objacc = new Account(Name = 'ABC' + i);
    acclist.add(objacc);
}

insert acclist;

list<Contact> conlist = new list<Contact>();

for(Account objacc :acclist){
    Contact objcontact = new Contact();
    objcontact.AccountId = objacc.id;
    objcontact.LastName = objacc.Name;
    conlist.add(objcontact);
}

insert conlist;
     }

}

Please Mark it As Best Answer if it Helps
Thank you!
Arun Kumar 1141Arun Kumar 1141
Hi Tushar, 
Try Below Code
public class createAccAndCon{
     public static void demoFun(){
         List<Account> accList = new List<Account>();
         List<Contact> conList = new List<Contact>();

         for(Integer i = 0; i<5; i++){
         Account acc = new Account();
         acc.Name = 'Test' + i;
         accList.add(acc);
         }
 
        insert accList;
        for(Account acc : accList){
         Contact con = new Contact();
         con.LastName = 'con test';
         con.AccountId = acc.Id;
         conList.add(con);
         }

        insert conList;
  }
}


Please mark it as best answer if it helps.
Thanks,