I'm following this page in the documentation for creating parent and child records in a single statement using foreign keys. It works for the Account and Opportunity scenario. But in the scenario wherein the child is not a standard object, it doesn't work.
For example, what I did is:
// The parent
Case parentCase = new Case();
parentCase.ExternalId__c = 'external_id_123abc';
// The case that will act as the foreign key that will connect the parent and the child
Case caseReference = new Case(ExternalId__c = 'external_id_123abc');
// The child
My_Custom_Object__c co = new My_Custom_Object__c();
cs.Name = 'test';
cs.Case__c = caseReference;
This code won't compile because cs.Case__c = caseReference
would throw an error of Illegal assignment from Case to Id
. Not sure how to go around this error.
The main objective here is to lessen the the soql statements that I need to fire. With this approach, I can create a parent and all of the dynamically created children at runtime.