Saturday, July 1, 2017

System.ListException: Before Insert or Upsert list must not have two identically equal elements

We will receive this error when your adding same instance of record to list twice i.e.If your adding same record twice to the list you will end up with error.

Sample Code With Error

List<Case> listCase = new List<Case>();
Case cs = new Case();
cs.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Bus').getRecordTypeId();
cs.Status ='Approved';
cs.Origin = 'Inbound Call';
listCase.add(cs);

Case cs1 = new Case();
cs1.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Bus').getRecordTypeId();
cs1.Status ='Approved';
cs1.Origin = 'Inbound Call';
listCase.add(cs);  // I should add cs1 instance but I added cs which are already in list

insert listCase;

If you run the above code you will receive an error while inserting System.ListException: Before Insert or Upsert list must not have two identically equal elements ,that is because of adding same case record twice to the list ,you can see duplicate element in yellow color where actually it should be cs1 but added cs which is already there in list.

To avoid this error you can cross check your code whether your adding some where same instance of object twice to the list.

Error Free Code


List<Case> listCase = new List<Case>();
Case cs = new Case();
cs.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Bus').getRecordTypeId();
cs.Status ='Approved';
cs.Origin = 'Inbound Call';
listCase.add(cs);

Case cs1 = new Case();
cs1.RecordTypeId = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Bus').getRecordTypeId();
cs1.Status ='Approved';
cs1.Origin = 'Inbound Call';
listCase.add(cs1);   //Corrected here adding cs1 instance to list 

insert listCase;


Thanks for visiting..hope this helps you!

1 comment: