Search code examples
c#asp.nettransactionstransactionscoperollback

Can we Call Two diiferent methods in Transaction scope in asp.net?


Hello i am new to Transaction Scope in C#. i have two insert queries one belongs to UserAccountCreation where LoginCredentials are stored and another is Inserting Employee details with respective UserAccountID in Employee table as foreign key.

I have two different methods written to insert in UserAccount Table and after inserting into UserAccount the UserAccountID is feteched and Inserted into Employee table. Situation is When UserAccount Creation succeeds and Employee Creation fails, then it must ROLLBACK. So, i would like to know whether we can use Transaction scope and in between call these two Insert Methods? and can we rollback these methods which have called in this scope if error occurs. Sample Code:

private void CreateEmp()
{
  using (TransactionScope scope = new TransactionScope())
  {
    try
    {
        CreateUserAccount();
        CreateEmployee();
        scope.Complete();
    } 
    catch (TransactionAbortedException ex)
        {

    }
  }
}

Help Appreciated! Thanks in Advance!


Solution

  • you can call as many functions as you want in the transaction scope. If you want two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.