Understanding the "Entity is deleted" Error
The "Entity is deleted" error in Salesforce occurs when code attempts to reference or modify a record that has already been deleted. This typically appears as: "ENTITY_IS_DELETED, entity is deleted: []" and prevents the current operation from completing successfully.
Causes of the "Entity is deleted" Error
-
Referencing a record after deletion: The most common cause is when code attempts to reference a record that was previously deleted in the same transaction or by another process.
-
Duplicate deletion attempts: This happens when the same record is targeted for deletion multiple times, such as when deletion operations are placed inside loops.
-
Race conditions: When multiple processes or triggers attempt to delete the same record simultaneously, one may succeed while others receive this error.
-
Integration issues: When external systems or integrations try to update records in Salesforce that have been deleted since the last synchronization.
How to Handle the "Entity is deleted" Error
-
Check record existence before operations:
apexif (record != null && !record.isDeleted) { // Perform operations on the record } -
Bulk operations outside of loops: Always collect records to delete in a list and perform a single DML operation outside any loops:
apexList<SObject> recordsToDelete = new List<SObject>(); for(SObject record : records) { if(meetsDeletionCriteria(record)) { recordsToDelete.add(record); } } delete recordsToDelete; // Single deletion operation outside the loop -
Exception handling: Implement proper try-catch blocks to gracefully handle this error:
apextry { delete recordToDelete; } catch(DmlException e) { if(e.getDmlType(0) == StatusCode.ENTITY_IS_DELETED) { // Handle the situation where the record is already deleted System.debug('Record was already deleted'); } else { throw e; // Re-throw if it's a different error } } -
Implement record locking mechanisms: For complex operations involving multiple processes, consider using a locking pattern to prevent concurrent modifications.
Conclusion
The "Entity is deleted" error occurs when your code interacts with records that no longer exist in the database. By implementing proper existence checks, using bulk operations outside of loops, and adding appropriate exception handling, you can avoid this error and make your Salesforce applications more robust.