[SalesForce] error while trying to upsert a list of Sobjects

I am trying to perform the following procedure:

String tipoInt = 'Account';

List<SObject> sl = new List<SObject>();

Sobject so = Schema.getGlobalDescribe().get(tipoInt).newSObject();
so.put('name', 'Endrit');
so.put('Test_External_Id__c', '1');
sl.add(so);

Sobject so2 = Schema.getGlobalDescribe().get(tipoInt).newSObject();
so2.put('name', 'Dori');
so2.put('Test_External_Id__c', '2');
sl.add(so2);

upsert sl  Account.Fields.Test_External_Id__c;

According to this reference: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml_section.htm#apex_dml_upsert

This code should work. Instead it returns the following error:

Upsert with a field specification requires a concrete SObject type

I am choosing a different path to avoid this obstacle, but if I could solve it through this approach, would save me a lot of work.

Best Answer

The error message tells you all you need to know. To use upsert with an external ID field you need to be upsetting a list of a concrete type, e.g. Account, rather than a list of sObjects.

If you need to upsert a list of generic sObjects then you can't specify an external ID field and must instead rely on the standard Salesforce ID field.

From your example it's hard to see why you are doing things the way you are. Both of the records are Account objects and you are referencing a field on Account for the upsert.

You could change your code to the following and everything would be fine.

List<Account> sl = new List<Account>();

Account so = new Account(Name = 'Endrit', Test_External_Id__c = '1'); sl.add(so);

Account so2 = new Account(Name = 'Dori', Test_External_Id__c = '2'); sl.add(so2);

upsert sl Account.Fields.Test_External_Id__c;
Related Topic