Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save lfreeland/08854c27859362f42cc3de3bfb2423ad to your computer and use it in GitHub Desktop.

Select an option

Save lfreeland/08854c27859362f42cc3de3bfb2423ad to your computer and use it in GitHub Desktop.
Upsert List<SObject> With External Id And No "AllOrNothing" Fix
public static List<Database.UpsertResult> upsertListSObjectsWithExternalIdNoAllOrNothingErrorExampleFix() {
/* To resolve the System.TypeException: DML on generic List<SObject> only allowed for insert, update or delete"
error, dynamically instantiate the List of SObject to a list of a concrete SObject type.
*/
Account a = new Account(
Name = 'Example Company',
External_Id__c = 'ExampleCompany'
);
Schema.SObjectType objectType = a.getSobjectType();
Schema.DescribeSObjectResult objectDescribe = objectType.getDescribe();
String objectName = objectDescribe.getName();
Type sObjectListType = Type.ForName('List<' + objectName + '>');
List<SObject> records = (List<SObject>) sObjectListType.newInstance();
records.add(a);
Schema.SObjectField f = Account.Fields.External_Id__c;
// Runs Successfully.
return Database.Upsert(records, f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment