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
Mohammad Hussain 7Mohammad Hussain 7 

Insert master and detail records in a single insert statement for custom objects

I am trying to insert master and detail records in a single insert statement. As a reference i took this example. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_foreign_keys.htm
When i excute the example provided here in my dev org it works. But, when i implement the same using custom objects not able to compile the class.  

newOpportunity.Account = accountReference; //I get error in this line for custom objects

If I am using custom objects how can i make this line work? I was thinking this should be parent id but, it is not it gives illigal assignment error.

 
Raj VakatiRaj Vakati
You can insert like this
 
Account__c testAcct = new Account__c(Name = 'My Test Account');
     insert testAcct;

    // Creates first opportunity
    Opportunity oppt = new Opportunity(Name ='New mAWS Deal',
                            Account__c = testAcct.ID,
                            StageName = 'Customer Won',
                            Amount = 3000,
                            CloseDate = System.today()
                         );

   insert oppt;

 
Mohammad Hussain 7Mohammad Hussain 7
Thanks for the quick response. This will work but, I dont want to insert parent first and then insert child. Also, i wanted to use external id to relate parent and child records as showen in the example. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_foreign_keys.htm