2

I am trying to test a trigger which works on Account Contact Relationship so I want to perform the following:

  • Insert an account
  • Insert a contact
  • Insert an account contact relationship (my trigger performs some textual extraction to find out account and contact)

My trigger however generates an exception:

System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, You can't associate a private contact with a company.: [ContactId]

This is the code that generates the exception:

    Account account = new Account(Vat_Code__c = 'Examplevat' ,Name = 'Example company2');
    insert(account);
    Contact contact = new Contact(FirstName  = 'John', LastName = 'Smith', Fiscal_Code__c = 'MyFiscalCode1');
    insert(contact);
    Test.startTest();
    AccountContactRelation relation = new AccountContactRelation(SurrogateId__c = 'MyFiscalCode1_Examplevat_Owner');
    insert(relation);
    Test.stopTest();

Is it necessary to have a primary account connected to the company before I could have a secondary connection?

  • Please post your code here – Samir Mar 9 '17 at 17:26
  • Hard to tell with your requirement, exact cause of the error. Can you please enter your code? – Mahmood Mar 9 '17 at 17:27
  • My code is there, I create an account, I create a contact without an account. I created an account contact relation and this fails. – Edmondo1984 Mar 9 '17 at 17:29
3

The Contact should be created with the AccountId field populated from the Account that you just created. Once you do that, your problem should disappear. Just change the following line in your code:

Contact contact = new Contact(FirstName  = 'John', LastName = 'Smith', accountId = account.Id, Fiscal_Code__c = 'MyFiscalCode1');
  • I have contacts that are not forcely related to an account then I import from a database the relationship. So what I need to do seems: if the contact has no account, set the relationship, if not, create the AccountContactRelation? – Edmondo1984 Mar 9 '17 at 17:38
  • Your contact first needs to be associated with the account via the accountId before you can set other relationships such as AccountContactRelation since the former is the primary relationship used by Salesforce between Accounts and Contacts. Also, your contact needs to have an owner. You didn't post the rest of your code. Use a RunAs user in your test that's appropriate for the context the trigger will run in. – crmprogdev Mar 9 '17 at 17:40
  • I think the explanation is clear now. You need a Primary Account in order to have secondary account or it won't work. – Edmondo1984 Mar 9 '17 at 17:49
  • Exactly! You got it now. :) – crmprogdev Mar 9 '17 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.