Tuesday, May 21, 2013

Perform DML Using External ID

Perform DML Using External ID

If you want to create a Contact associate with an Account without using AccountId field then you must have an External Id on Account object in order to create a Contact record.

It is not Efficient Code:

The following code is creating a Contact record by querying an Account record. However, because it uses a SOQL query, it is not as efficient. If this code was called multiple times, it could reach the execution limit for the maximum number of SOQL queries.
Sample Code:
Account refAcct = [SELECT Id FROM Account WHERE externalId__c='12345' LIMIT 1];
Contact c = new Contact(Account = refAcct.Id);
insert c;

Efficient Code:
The following code is equivalent to the code above. However, because it does not use a SOQL query, it is efficient.
Sample Code:
Account refAcct = new Account(externalId__c = '12345');
Contact c = new Contact(Account = refAcct, LastName = 'Kay');
insert c;
Note: This inserts a new contact with the AccountId equal to the account with the external_id equal to ‘12345’. If there is no such account, the insert fails.