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
Pradeep Pradhan 21Pradeep Pradhan 21 

create account,contact, and user in bulk in apex

hello i have solved this way. please help me if u have any other best possible ways.
      List<Account> accList = new List<Account>();
        for(Integer i=0; i<250; i++){

            Account acc = new Account();
            acc.Name= 'AccName'+ i;
           // acc.FEMA_ID__c = '123456789' +i;
            accList.add(acc);
        }

        insert accList;

        // Create Contacts
        List<Contact> conList = new List<Contact>();

        for (Account acc : accList){

            Contact con = new Contact();
            con.FirstName = 'fName';
            con.LastName = 'lName';
            //con.FEMA_ID__c = '123456789' +i;
            con.Accountid = acc.id;
            conList.add(con);
        }   
        insert conList;
    }

}
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Pradeep,

Yes that is the best way to code. You are adding the all the ietms to list and inserting list at once by this you are following best pratice.

In the above code no of DMLs will be only 2. 

If this solution helps, please mark it as best answer. If you have any doubts on this please post them .

Thanks,

 
mukesh guptamukesh gupta
Hi prdeep,

Please follow below code:-

if we are using List in DML then first we need to check the side of list for best approach:-
List<Account> accList = new List<Account>();
        for(Integer i=0; i<250; i++){

            Account acc = new Account();
            acc.Name= 'AccName'+ i;
           // acc.FEMA_ID__c = '123456789' +i;
            accList.add(acc);
        }

 if(accList.size() > 0)
        insert accList;

        // Create Contacts
        List<Contact> conList = new List<Contact>();

        for (Account acc : accList){

            Contact con = new Contact();
            con.FirstName = 'fName';
            con.LastName = 'lName';
            //con.FEMA_ID__c = '123456789' +i;
            con.Accountid = acc.id;
            conList.add(con);
        }   
 if(conList.size() > 0)
        insert conList;
    }

}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh