How to create a PersonAccount in salesforce using Apex code
RecordType personAccountRecordType = [SELECT Id FROM RecordType WHERE Name = 'Person Account' and SObjectType = 'Account'];
Account newPersonAccount = new Account();
// for person accounts we can not update the Name field instead we have to update the FirstName and LastName individually
newPersonAccount.FirstName = 'Fred';
newPersonAccount.LastName = 'Smith';
newPersonAccount.RecordType = personAccountRecordType;
insert newPersonAccount;
You will need to insert Account of RecordType of Person Account .Use developer name of record type as best practice.
If your code is in a Managed Package then you will get errors when you try to create a managed package because you cannot reference PersonAccount fields in a managed package. You will need to reference the fields dynamically to solve this.
The fields can be set like this:
newPersonAccount.put('FirstName', 'Fred');
Just a small correction, now we have a method to retrieve record types by developer name without performing SOQL queries. So, we could do the next:
Id personAccountRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('PersonAccount').getRecordTypeId();
Account newPersonAccount = new Account();
newPersonAccount.FirstName = 'Fred';
newPersonAccount.LastName = 'Smith';
newPersonAccount.RecordTypeId = personAccountRecordTypeId;
insert newPersonAccount;