[SalesForce] INVALID_FIELD, Foreign key external ID not found – Inserting Related Records via External Id

I am trying to insert related records via an External Id. i am using an approach described here where we create an empty parent object with the same external Id like the "real" parent. It is a self-relationship and i am using dynamic apex to make it usable for multiple objects.

Type accountType = Type.forName('Account'); // lets use Account as an example

SObject realParent = (SObject) accountType.newInstance(); // creating the parent
realParent.put('Name', 'myName');
realParent.put('ExtId__c', 'A876');

SObject emptyParent = (SObject) accountType.newInstance(); // creating the reference to the parent
emptyParent.put('ExtId__c', 'A876');

SObject child = (SObject) accountType.newInstance(); // creating the child
child.put('Name','otherName');
child.put('ExtId__c','A123');
child.putSObject('ParentAccount__r', emptyParent); // relating child to Parent

List<SObject> records = new List<SObject> {realParent, child};
insert records;

This works fine for other relationships and also if the parent is already existent in the database. However for this self-relationship the insert fails with following message:

Insert failed. First exception on row 1; first error: INVALID_FIELD,
Foreign key external ID: a876 not found for field ns__ExtId__c in
entity Account: [] Class.ns.myClassName.myMethodName: line 27,
column 1

Line 27 column 1 refers to the dml insert statement.

Has anyone experienced similar issues or an idea how to solve this? Any help is much appreciated.

Best Answer

Take a look at Creating Parent and Child Records in a Single Statement Using Foreign Keys (emphasis mine):

You can create related records that are up to 10 levels deep. Also, the related records created in a single call must have different sObject types. For more information, see Creating Records for Different Object Types in the SOAP API Developer's Guide.