What is mixed DML operation error in apex?
When we perform DML operation on setup and non-setup objects in a single transaction then we get mixed DML operation error.
For example: If we are trying to insert a record in Account object as well as in User object in a single transaction, we will encounter mixed DML error.
Have a look at the below code that will produce mixed DML error:
Public Class AccountController {
public static void addAccountAndUser() {
Account acc = new Account();
acc.Name = 'Vikram Singh Rathore';
Insert acc;
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User'];
UserRole r = [SELECT Id FROM UserRole WHERE Name = 'COO'];
User u = new User();
u.alias = 'vicky';
u.email = 'vsrathore86.singh@gmail.com';
u.emailencodingkey = 'UTF-8';
u.localesidkey = 'en_US';
u.profileId = p.Id;
u.userroleId = r.Id;
u.username = 'vikramsingh';
u.lastname = 'rathore';
u.timezonesidkey = 'America/Los_Angeles';
Insert u;
}
}
Comments
Post a Comment