[SalesForce] INVALID_CROSS_REFERENCE_KEY, Can not select a person account: [AccountId]

My test class for inserting contact is

static testmethod void invoicetest(){

string strrecord = [select id from RecordType where SobjectType='Account' AND IsPersonType=True limit 1].id;
        system.debug('strrrrr'+strrecord);

        Account acc = new Account(firstName='test',LastName='Acc',Recordtypeid=strrecord);
        insert acc;
        contact con = new contact(firstname='Test',LastName='Contact',Salutation='Mr',Accountid=acc.id);
        insert con;

Then I'm getting error as System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Can not select a person account: [AccountId]

How to come out of this!!!!!!!!!

My Apex Class is

conlist = new contact[0];
con.lastname = billing.billinglastname;
con.firstname = billing.billinglastname;
conlist.add(con);
 if(con.lastname != null){
                  insert conlist;   //getting error here   
}

Best Answer

When working with Person Accounts you do not need to set the Contact separately; that is all handled automatically by Salesforce. Just create a Person Account and use that for testing:

static testmethod void invoicetest(){

   RecordType myRecordType = [select id from RecordType where SobjectType='Account' AND IsPersonType=True limit 1];

   Account acc = new Account(
     FirstName='test',
     LastName='Acc',
     Recordtypeid=myRecordType.Id);
   insert acc;
}

Edit: Modified SOQL for retrieving RecordType.

Update

Your Apex class is dealing with Contacts, your test class is trying to assign Contacts to Accounts, but your question is relating to Person Accounts. I believe both your Apex class and the tests should only be creating Accounts with your Person Account Record Type.

Related Topic