Salesforce MIXED_DML_OPERATION
The MIXED_DML_OPERATION error in Salesforce occurs when you attempt to perform a DML (Data Manipulation Language) operation on setup objects (such as User, Profile, UserRole, Group, etc.) within the same transaction as DML operations on regular sObjects (standard or custom objects).
This restriction is in place to maintain the integrity and security of Salesforce data because setup objects control system-wide settings and configurations that could impact multiple users and processes.
Here's how you can handle the MIXED_DML_OPERATION error:
Separate Setup and Non-Setup DML Operations: Split your DML operations into separate transactions, with one transaction handling DML operations on regular sObjects and another transaction handling DML operations on setup objects.
public void handleMixedDML() {// Perform DML operations on regular sObjects
List<Account> accountsToUpdate = [SELECT Id, Name FROM Account LIMIT 10];
// Perform DML operations on standard or custom objects
update accountsToUpdate;
// Perform DML operations on setup objects in a separate transaction
System.runAs(new User(Id = UserInfo.getUserId())) {
// Perform DML operations on setup objects
// For example, updating a User record
User currentUser = [SELECT Id, Email FROM User WHERE Id = :UserInfo.getUserId() LIMIT 1];
currentUser.Email = 'newemail@example.com';
update currentUser;
}
}
Use System.runAs for Setup Object DML: If you need to perform DML operations on setup objects within the context of a user, you can use the System.runAs method to execute the setup object DML operations in a separate context.
public void handleMixedDMLWithRunAs() {// Perform DML operations on regular sObjects
List<Account> accountsToUpdate = [SELECT Id, Name FROM Account LIMIT 10];
// Perform DML operations on standard or custom objects
update accountsToUpdate;
// Perform DML operations on setup objects using System.runAs
System.runAs(new User(Id = UserInfo.getUserId())) {
// Perform DML operations on setup objects
// For example, updating a User record
User currentUser = [SELECT Id, Email FROM User WHERE Id = :UserInfo.getUserId() LIMIT 1];
currentUser.Email = 'newemail@example.com';
update currentUser;
}
}
By separating DML operations on setup objects from DML operations on regular sObjects or using System.runAs, you can avoid the MIXED_DML_OPERATION error and ensure that your Salesforce transactions execute successfully.
Comments
Post a Comment