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
Novo_ArtisNovo_Artis 

Dynamic DML (Referencing objects before insertion)

I have been wondering if it is possible to relate objects without inserting the parent first.

 

I hope to achieve something similar to this...

 

List<Contact> cList = new List<Contact>();
cList.add(new Contact(FirstName = 'Jeff'));
cList.add(new Contact(FirstName = 'John'));
cList.add(new Contact(FirstName = 'Joe'));

Account a = new Account(contacts = cList);

insert a;

 

I know I could insert the account, reference it in each contact then insert the contacts.

The issue with that is I have to use more DML statements and it also forces me to write lots of loops to handle bulk inserting of new objects with children.

Account a = new Account();
imuino2imuino2

You cant do that becuase you need the Account Id before inserting the contacts.

Salesforce doesn't do it automatically.

 

Ignacio.

d3developerd3developer

Novo,

 

You can bulk insert the Contacts though.

 

Account a;

...

insert a;

List<Contact> clist = new List<Contact>();

for(...)

    clist.add(new Contact(name = 'xyz', AccountId = a.id));

 

insert clist.