5

I have 3 objects. Account, Contact and AccountContact(custom).

When I try to insert account and contact using one insert statement as follows, it works perfectly

Account a = new Account(Customer_ID__c='12345',name='accounttest');
Contact c = new Contact(account=new Account(Customer_ID__c='12345'),lastname = 'test', externalId__c='extId');

insert new List<sObject>{a, c};

Now, I am trying to insert custom object(Accountcontact) which has lookup to contact as follows:

Account a = new Account(Customer_ID__c='12345',name='accounttest');
Contact c = new Contact(account=new Account(Customer_ID__c='12345'),lastname = 'test', externalId__c='extId');
AccountContact__c ac = new AccountContact__c(name='testing', Contact__c = new Contact(externalId__c='extId'));

insert new List<sObject>{a, c, ac};

Above code throws an error "Invalid initial expression type for field AccountContact__c.Contact__c, expecting: Id"

Is there a way to achieve inserting all 3 in single DML call. Thanks

8

You need to use a related field Contact__r to associate the Contact to AccountContact__c.

Try below code,

List<sObject> records = new List<sObject>();
records.add(new Account(AccountExternalId__c='1234555', Name='ABCD Company'));

records.add(new Contact(account=new Account(AccountExternalId__c='1234555'),lastname = 'Testlast', ContactExternalId__c='3525'));

records.add(new AccountContact__c (Contact__r = new Contact(ContactExternalId__c='3525')));

insert records;
6

You need to use the name pointing reference. Here, that would be Contact__r.

It might be more clear if you look at how it works if you set the value dynamically: you can either call set with the Id, or setSObject with the record.

AccountContact__c junction = new AccountContact__c();
junction.set('Contact__c', someContactId);
//OR
junction.setSObject('Contact__r', someContactRecord);

Also, note that you can always get the name of this relationship through the describe.

DescribeFieldResult describe = AccountContact__c.Contact__c.getDescribe();
system.debug(describe.getRelationshipName());

In your working case, the field has an API Name of AccountId, and a Relationship Name of Account. What you're trying to do in the junction object is analogous to if you modified your working snippet as follows:

Contact record = new Contact(AccountId=new Account(...));

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.