Created
May 12, 2016 12:22
-
-
Save lfreeland/08854c27859362f42cc3de3bfb2423ad to your computer and use it in GitHub Desktop.
Upsert List<SObject> With External Id And No "AllOrNothing" Fix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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