System.TypeException: DML on generic List only allowed for insert, update or delete

Published in Troubleshooting Exceptions

When the error will appear?
You cannot upsert a List of SObject.

How to reproduce the issue?
Nothing special, just create a list of SObject, add one Account record and try to upsert the list. Try to execute the next code in the Anonymous Window.

List<SObject> recordsList = new List<SObject>();
recordsList.add(new Account(
    Name = 'Buster'
));

upsert recordsList;

Is there any workaround?
The workaround for this problem casts a list of records to a specific type.

public inherited sharing class ObjectUtils {
    // dynamically instantiate the List of SObjectіs to a list of a concrete SObject type.
    public static List<SObject> castToType(List<SObject> sourceList, Schema.SObjectType targetType) {
        List<SObject> resultCasttList = (List<SObject>) System.Type.forName('List<' + targetType + '>').newInstance();
        resultCasttList.addAll(sourceList);    
        return resultCasttList;
    }
}
Let's modify our code using the ObjectUtils class.
List<SObject> recordsList = new List<SObject>();
recordsList.add(new Account(
    Name = 'Buster'
));

List<SObject> convertedRecordsList = ObjectUtils.castToType(recordsList, Account.SObjectType);
upsert convertedRecordsList;

Comments powered by CComment