How to create transaction with asp.net identity?

前端 未结 3 823
無奈伤痛
無奈伤痛 2020-12-31 11:28

I am doing registration on which i am asking for 5 things:

FullName,EmailId,Password,ContactNumber,Gender

Now emailid and password i am stor

3条回答
  •  长发绾君心
    2020-12-31 11:43

    You can solve it with TransactionScope class:

    using (TransactionScope scope = new TransactionScope())
    {
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await this.UserManager.AddToRoleAsync(user.Id, model.Role.ToString());
            string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");
            return View("DisplayEmail");
        }
        scope.Complete();
    }
    

    So, both actions will be done in one transaction and if method Comlete does not call, both actions will be canceled (roolback).

    If you want to solve it with EF only (without TransactionScope), you need to refactor your code. I don't know implementation of class UserManager and methods CreateAsync and AddToRoleAsync, but I guess that they creates new DBContext for each operation. So, first of all, for all transactional operations you need one DBContext (for EF solution). If you add this methods, I'll modify my answer according to EF solution.

提交回复
热议问题