6

When I try to set the lookup field with the external id, everything works fine:

Account a = new Account();
a.AccountExternal_ID__c = 'abc';

Car__c c = new Car__c();
c.Account__r = a;
insert c;

But, when I want to do it with the base SObject type, I get an exception `Invalid field Account__r for Car__c:

Account a = new Account();
a.AccountExternal_ID__c = 'abc';

Car__c c = new Car__c();
Sobject so = c;

so.put('Account__r', a);
insert so;

Is there any way to make it work, without querying the accounts?

1 Answer 1

5

You need to use SObject.putSobject instead of just SObject.put. The former is used to set reference fields, and is even explicitly mentioned as the preferred method of setting SObject values for External Id values:

Sets the value for the specified field. This method is primarily used with dynamic DML for setting external IDs. The method returns the previous value of the field. (Emphasis mine).

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.