Tuesday, April 12, 2011

DML error: Name not specified

When trying to upsert a list of records via Apex, I received a slew of "Name not specified" errors on every single one of the records.  The Database.Error.getStatusCode() instance method returned "MISSING_ARGUMENT", and the Database.Error.getMessage() instance method returned "Name not specified".

My upsert was constructed as follows:
upsertResults = Database.upsert(applications,
        Application__c.Unique_External_Application_ID__c, false);

Application__c is a custom object, and Unique_External_Application_ID__c is a custom field that is set to be an external ID. applications is my List that I was trying to upsert.

Basically, after a few hours of frustration and asking for help on #salesforce, I determined that the error came from the fact that I was trying to set a Lookup field by specifying an external ID on the related object. An example is shown below:
Application__c application = new Application__c();
application.Start_Term__r = new Term__c(Banner_Code__c = '201115');

I had simply assumed this would work, since I knew that a lookup field can be set by setting the custom field __r to new sObject(Name = recordName). Apparently I was 100% wrong.


But I did create an idea out of this whole mess: enable Apex DML to set Lookup or Master-Detail by external ID

I wish I could recall the idea, because apparently the error was the result of my putting a null value into the Name field when specifying the related record. Essentially, my code was trying to execute the following:
application.Program__r = new Program__c(Name = null);

Specifying an external ID in the following manner does work:
application.Term__r = new Term__c(Banner_Code__c = '201115');