+ Start a Discussion
dshpadshpa 

How to get the Contact of a Person Account

I work with Person Accounts in my code. To get the Contact of such Account I use the following:

 

 

Contact personAccountContact = anyPersonAccount.Contacts[0];

 

 

That works. But I encountered quite unexpected problem when testing my code. I create a test Person Account like this:

 

 

Account account = new Account();
account.FirstName = 'First Name';
account.LastName = 'Last Name';
account.RecordTypeId = [
	select Id
	from RecordType
	where (Name='Person Account')
	and (SobjectType='Account')
].Id;
insert account;

 

But when I try to get the Contact of the created Account as described above I fails. The number of Contacts for created Account is 0. I debugged this code and found that RecordTypeId field is assigned with the proper value, but IsPersonAccount field is false and PersonContactId field is null. Where am I wrong?

 

jaganjagan

Have you tried making IsPersonAccount as true while inserting the account ...like account.IsPersonAccount=true; ??

dshpadshpa

Sure. But this field is read-only. Besides in SFDC docs they assert that it's sifficient to assign LastName field instead Name field for creating Person Account. But I see that's not enough! I can't normally test my working code. Any other suggestions?

jaganjagan

Not sure of where it went wrong.....but the code which you have pasted worked out for me.... I just copied that code and tried .....it inserted a person account (with isPersonAccount=true ) and I also got the contact for that account when i debug the below line....

Contact personAccountContact = anyPersonAccount.Contacts[0];