justme
justme

Reputation: 336

How to rollback changes in ASP.NET Core 2

I need help with my code. Currently in my ASP.NET Core 2 application, I create user this way:

var result = await _userManager.CreateAsync(user, password);

If succeeded I add user to roles and I do some other operations on database.

        if (result.Succeeded)
        {
           var roleResult = await _userManager.AddToRoleAsync(user,"Admin");
           if(roleResult.Succeeded)
           {
            await _repository.AddToGroup("External");
            await _repository.AssignToRoom(RoomEnum.Office);
           }
        }

If for some reason AddToGroup() or AssignToRoom() will not be succeeded, user should not be created and should not be added to roles as well. I would like to undo createing user operation completly. How to achive that?

Upvotes: 0

Views: 1666

Answers (1)

Vahid Farahmandian
Vahid Farahmandian

Reputation: 6566

You need to use TransactionScope class. Using this class you will have Commit or Rollback methods which will help you to commit the whole transaction or rollback the whole transaction.

read more about TransactionScope:

  1. https://learn.microsoft.com/en-us/dotnet/api/system.transactions.transactionscope?view=netframework-4.8
  2. https://learn.microsoft.com/en-us/ef/ef6/saving/transactions#combining-several-operations-into-one-transaction-within-the-same-context

Upvotes: 1

Related Questions