1 year ago

#371088

test-img

Ardians.sh

is doing a commit at the end of a line of code a good thing?

I have code like this, where the commit is done at the end of the line. the goal is that when an error occurs while sending an email, then the commit will not be performed but will rollback. is something like this a good thing? or is there a better way than the one I'm currently implementing?

    public async Task<IActionResult> Register(RegisterAccount register)
    {                           
        MyAccount myAccount = new();
        using var transaction = _dbContext.Database.BeginTransaction();
        bool afterRegister = false;
        try
        {
            //code for check account                    
        
            //code for set value register account
        
             afterRegister = true;
             _dbContext.Database.OpenConnection();
            transaction.CreateSavepoint("register");
        
             _dbContext.MyAccounts.Add(myAccount);
             await _dbContext.SaveChangesAsync();
        
            _dbContext.Database.CloseConnection();
        
            //code for send email
        
            transaction.Commit();
        
            return RedirectToAction("RegisterConfirm", "Account", new { emailConfirm = myAccount.Email });
        }
        catch(Exception e)
        {
            if (afterRegister)
            {
                transaction.RollbackToSavepoint("register");
            }
        
             return View();
        }
    }

thank you for answering my question. good luck always

.net-core

transactions

commit

0 Answers

Your Answer

Accepted video resources