+ Start a Discussion
BerginBergin 

Binding account to contact

What's wrong in this code? 
I'm trying to add contact to a Business account.

public void AddContact(Account account, string firstName, string lastName)
    {
      Contact NewContact = new Contact();
     
      NewContact.FirstName = firstName;
      NewContact.LastName = lastName;
      NewContact.Account = account;
          
            System.debug('Before Insert Biz Contact123 : ' + firstName + ' - ' + lastName + ' - ' + account);
      //Insert new contact
      insert NewContact;

            System.debug('After Insert Biz Contact123 : ' + NewContact.FirstName + ' - ' + NewContact.LastName + ' - ' + NewContact.Account.Id);
    }

This is what I see in the log, but the account is not bound to the contact.

|USER_DEBUG|[143]|DEBUG|Before Insert Biz Contact123 : James - San - Account:{Name=Jaas, RecordTypeId=012Z0000000D69aIAC, Id=001Z000000k7IA7IAM}
|USER_DEBUG|[150]|DEBUG|After Insert Biz Contact123 : James - San - 001Z000000k7IA7IAM

Best Answer chosen by Bergin
RitikaBhrgvRitikaBhrgv
Hi bjrp,

NewContact.Account refers to the relationship and not the field to be associated on Contact. To associate the account, use the following syntax :

NewContact.AccountId = account.Id;

All Answers

RitikaBhrgvRitikaBhrgv
Hi bjrp,

NewContact.Account refers to the relationship and not the field to be associated on Contact. To associate the account, use the following syntax :

NewContact.AccountId = account.Id;
This was selected as the best answer
BerginBergin
Hi Ritika, thanks. I realized soon after I posted the question. Thanks for your response though.