Not able to insert parent and child record using database.Insert in one go

apexdatabase.insertdml

In my case eSales_Order__c is the Parent object and having Master detail relation ship to eSales_Order_Line__c. So I am trying to insert into both Parent and child at same time . I am having a common field named BulkInsert__c in both the objects and I am trying to insert as like below

    List<eSales_Order__c> lstSalesOrderToCreate=new List<eSales_Order__c>();
    List<eSales_Order_Line__c> lstCreateSalesOrderLineInitial= new List<eSales_Order_Line__c>();
    

  for(Id oppId:OppIds){       
        eSales_Order__c  salesOrder= new eSales_Order__c();
        salesOrder.Billing_Date__c=System.Today().addMonths(1).toStartofMonth().addDays(-1);
        salesOrder.Status__c='Pending';
        salesOrder.BulkInsert__c='1';
        salesOrder.Account__c=MapOppLineItem.get(oppId).Opportunity.Accountid;
        salesOrder.Opportunity__c=oppId;
        lstSalesOrderToCreate.add(salesOrder);
             
        for(OpportunityLineItem oppLineItem: lstOpplIneItem){
            if(oppLineItem.OpportunityId== oppId){
                eSales_Order_Line__c salesLine= new eSales_Order_Line__c();
                salesLine.eSales_Order__c=salesOrder.Id;              
                salesLine.BulkInsert__c='1';
                salesLine.Unit_Price__c=oppLineItem.UnitPrice;              
                lstCreateSalesOrderLineInitial.add(salesLine);
            }
        }
        for(OpportunityLineItemSchedule oppLineItemSchedule: lstOppLineItemSchedule){
            if(oppLineItemSchedule.OpportunityLineItem.OpportunityId== oppId){
                eSales_Order_Line__c salesLine= new eSales_Order_Line__c();
               if(oppLineItemSchedule.Installment__c == 1){
                   salesLine.eSales_Order__c=salesOrder.Id;
                   salesLine.BulkInsert__c='1';                   
                   salesLine.Unit_Price__c=oppLineItemSchedule.OpportunityLineItem.UnitPrice;                 
                   lstCreateSalesOrderLineInitial.add(salesLine);
                } 
               
            }
        }
        
    }

        if(!lstSalesOrderToCreate.IsEmpty()){
            SObject[] sobjList = new List<SObject>();
            sobjList.addAll(lstSalesOrderToCreate);
            sobjList.addAll(lstCreateSalesOrderLineInitial);         
            Database.SaveResult[] results = Database.insert(sobjList);
       }

But when I tried to execute the code I am always getting

Opportunity: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 1; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [eSales_Order__c]: [eSales_Order__c] Class.OpportunityTriggerHandler.CreateSalesOrderFromOppandPaymentSchedule:

Best Answer

I recommend you read and understand Creating Parent and Child Records in a Single Statement Using Foreign Keys. As long as your parent object has any External Id field, you can in fact do what you want. The mechanics are just a little different.

The basic structure looks like:

Parent__c parent = new Parent(External__c = 'foo');
Child__c child = new Child__c(
    Parent__r = new Parent__c(External__c = parent.External__c)
);
insert new List<SObject__c> { parent, child };

Notice that the Parent__c record we set in the lookup field (via Name Pointing Relationship) is newly constructed rather than reusing the parent instance already in memory. That is important in the real world context, because the External Id field should be the only one specified.

Create the parent reference sObject used only for setting the parent foreign key reference on the child sObject. This sObject has only the external ID field defined and no other fields set.


If you do not already have a convenient External Id field for this purpose, you can simply add a new field to make this pattern work and populate it with some UUID implementation.

Related Topic