// First create a ExterNalId__c as a custom field with External Id Options on Parent object.
List<SObject> sObjectLst = new List<SObject>();
// Create the parent reference. Used only for foreign key reference and doesn't contain any other fields.
Account accRef = new Account(ExterNalId__c = 'externalIdValue');
// Create a child record or many records
For(Integer i = 0 ; i<3;i++){
Contact con = new Contact();
con.Firstname = 'ConFirst'+i;
con.Lastname = 'ConLast'+i;
con.Account = accRef; // Assign this created parent reference to that parent relation field.
sObjectLst.add(con); // Add these child records in list.
}
// Create parent record with initializing required fields and externalId field.
Account acc = new Account(Name='Acc Name',ExterNalId__c = 'externalIdValue');
sObjectLst.add(acc); // Add parnet record in list.
// Insert list
Database.SaveResult[] results = Database.insert(sObjectLst); // Check results.
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
System.debug('Successfully created ID: '+ results[i].getId());
} else {
System.debug('Error: could not create sobject '+ 'for array element ' + i + '.');
System.debug(' The error reported was: '+ results[i].getErrors()[0].getMessage() + '\n');
}
}
Test
ReplyDelete