I want to insert Parent and Child Accounts in one DML statement. I know it can be done for related Contact/Account objects using External Id field, but it doesn't work in my case.
Running the following code
Account childAccount = new Account(Name='Child Account');
Account parentAccountRef = new Account(External_Id__c='123');
childAccount.Parent = parentAccountRef;
Account parentAccount = new Account(Name='Parent Account', External_Id__c='123');
Database.insert(new Account[] {parentAccount, childAccount});
I get the error:
System.DmlException: Insert failed. First exception on row 1; first error: INVALID_FIELD, Foreign key external ID: 123 not found for field External_Id__c in entity Account: []