Entity is deleted on apex merge
When merging two account records in Apex, a common error 'entity is deleted' can occur if a lookup field on the master account references the sub account being merged. This happens because after the merge, the sub account record no longer exists, causing the reference to break. The fix is to null out such lookup fields on the master account before performing the merge call. This simple adjustment avoids runtime errors and ensures smoother merge operations in Apex code.
- Merging accounts in Apex can cause 'entity is deleted' if lookup fields reference merged records.
- Before merging, null out lookup fields on the master record that reference the sub record.
- Create the sub account instance using its ID to pass into the merge statement.
- Wrap merge operations in try-catch to handle exceptions gracefully.
- This pattern prevents runtime errors and improves data integrity during merges.
Hey guys, Just a little quick fix post here, a silly little bug that took me a bit of time to hunt down (probably just because I hadn’t had enough coffee yet). Anyway, the error happens when trying to merge two accounts together. I was getting the error ‘entity is deleted’. The only thing that made my code any different from other examples was that, the account I was trying to merge was being selected by picking it from a lookup on the master. The basic code looked like this (masterAccount was being set by the constructor for the class, so it is already setup properly). try { Account subAccount = new Account(id=masterAccount. Merge_With__c ); merge masterAccount subAccount; mergeResult = 'Merge successful'; } catch (exception e) { mergeResult = e. getMessage (); } Can you spot the problem here? Yup, because the Merge_With__c field on the master account would now be referencing an account that doesn’t exist (since after a merge the child records get removed) it was throwing that error.