I have a rest class that creates Account records, related Contacts and a related Custom Object 'Customer__c'.
I am able to upsert Accounts based on an External Id. How can I upsert the Contact related list and Customer__c related list records based on External ids?
Here's the class:
@RestResource(urlMapping='/Order/*')
global with sharing class OrderWebServicesV2 {
private class OrderWrapper {
Account account;
list<ContactWrapper> contacts;
}
private class ContactWrapper {
Contact contact;
list<Customer__c> customers;
}
@HttpPost
global static String doPost() {
OrderWrapper container = (OrderWrapper)System.JSON.deserialize(
RestContext.request.requestBody.tostring(),
OrderWrapper.class);
Account acc = container.account;
upsert acc MyExternalId__c;
list<Contact> contactsToInsert = new list <Contact>();
for (ContactWrapper wcon :container.contacts) {
wcon.contact.accountId = acc.id;
contactsToInsert.add(wcon.contact);
}
upsert contactsToInsert;
//now wrapper list contains contact ids
list<Customer__c> customersToInsert = new list <Customer__c>();
for (ContactWrapper wcon :container.contacts) {
for (Customer__c customer :wcon.customers) {
customer.Contact__c = wcon.contact.id;
customersToInsert.add(customer);
}
}
upsert customersToInsert;
return acc.id;
}
}
How can I upsert the related lists using the same External Id 'MyExternalId__c'?
I tried using Database.insert but have not been successful. Thanks!