+ Start a Discussion
BinayakBinayak 

exception while inserting 2 related contacts same time

When i am trying to insert 2 contacts at 1 go using the external id field(extfld__c)..like

Contact c1 = new Contact(FirstName = 'F1',LastName='L1',extfld__c='e1');
Contact c2 = new Contact(FirstName = 'F2',LastName='L2',extfld__c='e2',ReportsTo=new Contact(extfld__c='e1'));
List<Contact> l = new List<Contact>();
l.add(c1);
l.add(c2);
try{
    upsert l;
}
catch(Exception e)
{
    System.debug('Exception::'+e.getMessage());
}

Its throwing exception:

First exception on row 1; first error: INVALID_FIELD, Foreign key external ID: e1 not found for field extfld__c in entity Contact: []
07:47:23.388 (388572000)|SYSTEM_METHOD_EXIT|[11]|System.debug(ANY)


But when trying with the Account and contact like:

Account a = new Account(name='Test Con',extfldAcc__c='1234TestAcc');
Contact c2 = new Contact(FirstName = 'F2',LastName='L2',extfld__c='e2',Account = new Account(extfldAcc__c='1234TestAcc'));
insert new List<Sobject>{a, c2};

its inserting(while extfldAcc__c is the external id field for Account).

Can any one help me for overcoming the exception while inserting 2 contacts at the same go.

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

Two options - insert by 'tier' - all those with no reports to first, then those that report to the first tier, then those that report to the second tier. Or insert everything without a reports to, then add the reports to and update them all.

All Answers

bob_buzzardbob_buzzard

I suspect its because when you insert an account and a contact, these are inserted by separate operations under the hood - e.g. the account gets inserted, all triggers workflow fire, then the contact and thus the account is present.  As you are inserting two contacts, this happens in a single operation and the triggers/workflow get both contacts passed through to them.  This means that the first contact hasn't been committed to the database when you attempt to insert the second.

BinayakBinayak

Any workaround for this?(except using 2 upsert/insert statements)

bob_buzzardbob_buzzard

You could look at an after insert trigger that fixes up the relationship, but that would have to carry out an update to its probably easier to break your insert out into two statements.

BinayakBinayak

But suppose I have 1000 records.Out of which 500 contacts have this ReportsTo field populated.They may be hierarchical (like A reports to B ,B reports to C,C reports to D).Then how to segregate?

bob_buzzardbob_buzzard

Two options - insert by 'tier' - all those with no reports to first, then those that report to the first tier, then those that report to the second tier. Or insert everything without a reports to, then add the reports to and update them all.

This was selected as the best answer