1

I have a weird situation in one of my classes. There are two custom objects and one of the objects holds a reference to the other. I am deleting records from the child objects.

Here is my code.

List<Line_Item__c> lineItems = [SELECT Id, Name FROM Line_Item__c WHERE Contract__c = 'a0g4D000000CbVKQA0'];
System.Debug('Before Deleting All Line Items '+ string.valueOf(lineItems.size()));
delete lineItems;
System.Debug('After Deleting All Line Items '+ string.valueOf(lineItems.size()));
System.Debug(lineItems.size());

The issue I am seeing is that the lineItems.size() is returning the same number of records before and after the delete statement. As a result of this, the code doesn't evaluate an if condition correctly. The way I expect this code to work is that the delete should just delete all the records from the line items object that satisfy the selection criteria. Unfortunately that is not happening in my case. The Debug statement is printing the same number before and after.

  • 4
    You are not deleting your list that is in memory. You are deleting the records on the table. If you re-query after your delete operation you will get what you are expecting. – Jesse Milburn Mar 6 '17 at 22:28
2

If you want to remove record from a collection, you need to use clear. Calling delete leaves the reference intact.

List<Line_Item__c> lineItems = [/*query*/];
lineItems.clear();
system.assertEquals(0, lineItems.size(),
    'The collection should be empty');

If you want to check the number of remaining records after a delete operation, as mentioned in the existing answer, you must requery.

List<Line_Item__c> lineItems = [/*query*/];
lineItems.clear();
system.assertEquals(0, [SELECT count() FROM Line_Item__c WHERE Id IN :lineItems],
    'The records should be deleted');
| improve this answer | |
0

You need to query after the delete

 List<Line_Item__c> lineItems = [SELECT Id, Name FROM Line_Item__c WHERE Contract__c = 'a0g4D000000CbVKQA0'];
System.Debug('Before Deleting All Line Items '+ string.valueOf(lineItems.size()));
delete lineItems;
List<Line_Item__c> lineItemsAFterDelete = [SELECT Id, Name FROM Line_Item__c WHERE Contract__c = 'a0g4D000000CbVKQA0'];
System.Debug('After Deleting All Line Items '+ lineItemsAFterDelete.size());
| improve this answer | |
  • Thank you for replying. A re-query is not required for me in this case. A clear will suffice. – abhi Mar 7 '17 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.