Scenario:
Product__c product = [SELECT Id, ProcurementGroup__r.Number__c FROM Product__c LIMIT 1]
product.ProcurementGroup__r = new ProcurementGroup__c(ExternalId__c = '123');
update product;
I am referencing a lookup record by external Id. This code works, if ProcurementGroup__c lookup is empty on the record. But if it already references something, I get this error:
FATAL_ERROR System.DmlException: Update failed. First exception on row 0 with id a07D000001D6BwGIAV; first error: INVALID_FIELD, Cannot specify both an external ID reference ProcurementGroup__r and a salesforce id, ProcurementGroup__c: []
As a workaround I tried to set ProcurementGroup__c to null:
product.ProcurementGroup__c = null;
product.ProcurementGroup__r = new ProcurementGroup__c(ExternalId__c = '123');
update product;
But I still get the same error. The only other workaround I can think of is to update object twice, first to remove reference, then to specify new reference.
Anyone has a better idea? Appreciate any suggestions.