Friday, May 20, 2016

APEX: Mixed DML Operations Error

You get the following exception or similar: "Insert failed. First exception on row 0; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): User, original object:  Product2"

In this case, you need to enclose your setup object in a system.runAs() operation as follows:

system.runAs(new User(Id = UserInfo.getUserId())) 
{
    ...your setup-object DML...
    User usr = new User();
    usr.UserName = 'Test';
    .....
    insert usr;
}

No comments:

Post a Comment