Hi kumar,
I know this approach is strange because you are still working with a List<SObject>, but when you assign it you can make it more specific (e.g. List<Account>) by using Type.forName and Type.newInstance methods.
public static void dynamicUpsert(List<SObject> records)
{
Schema.SObjectType sObjectType = records.getSObjectType();
if (sObjectType != null)
{
String listType = ‘List<‘ + sObjectType + ‘>’;
List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();
castRecords.addAll(records);
upsert castRecords;
}
}
The getSObjectType call may not be completely reliable, especially since some of these records are being inserted and hence won’t have ids. For that reason, it is probably better to accept sObjectTypeas an additional parameter instead of trying to determine it on the fly.
public static void dynamicUpsert(List<SObject> records, SObjectType sObjectType)
{
String listType = ‘List<‘ + sObjectType + ‘>’;
List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();
castRecords.addAll(records);
upsert castRecords;
}