You need to set the AccountId
and ContactId
values, not Account
and Contact
. In addition, you need to wait until after you insert them to set the relationship.
To do so, you're probably going to need to maintain a map of Case
id to Master_Id__c
. In addition, using a combined list for insert is going to work poorly for you if you have more than 5 records. More on that later.
List<Account> accounts = new List<Account>();
List<Contact> contacts = new List<Contact>();
Map<String, Case> masterIdToCase = new Map<String, Case>();
for (Case record : cases)
{
String masterId = util.getRandomString(20);
masterIdToCase.put(masterId, record);
// other logic
a.Master_Id__c = masterId;
accounts.add(a);
// other logic
c.Master_Id__c = masterId;
contacts.add(a);
}
insert accounts;
insert contacts;
for (Account a : accounts)
masterIdToCase.get(a.Master_Id__c).AccountId = a.Id;
for (Contact c : accounts)
masterIdToCase.get(c.Master_Id__c).ContactId = c.Id;
update masterIdToCase.values();
In regards to why you want to maintain separate lists, take a look at Things You Should Know about Data in Apex.
Creating Records for Multiple Object Types
As with the SOAP API, you can create records in Apex for multiple object types, including custom objects, in one DML call with API version 20.0 and later. For example, you can create a contact and an account in one call. You can create records for up to 10 object types in one call.
...
Records for multiple object types are broken into multiple chunks by Salesforce. A chunk is a subset of the input array, and each chunk contains records of one object type. Data is committed on a chunk-by-chunk basis. Any Apex triggers that are related to the records in a chunk are invoked once per chunk. Consider an sObject input array that contains the
You can only create 10 separate insert chunks, and every time you alternate creates a new chunk. Consider the following list, which counts for 12 chunks instead of 2:
insert new List<SObject> {
new Account(Name='A1'), new Contact(Name='C1'),
new Account(Name='A2'), new Contact(Name='C2'),
new Account(Name='A3'), new Contact(Name='C3'),
new Account(Name='A4'), new Contact(Name='C4'),
new Account(Name='A5'), new Contact(Name='C5'),
new Account(Name='A6'), new Contact(Name='C6')
};
Best Answer
You can't specify both an ID (in this case, null), and an external ID (which presumably would generate a non-null value). Do not specify both
Parent_Id__c
andParent_Id__r
on the same record.