Nyprez
Nyprez

Reputation: 173

Using a single transaction for multiple method C#?

Lets say I got an Insert-button where I got multiple method within it, where they read, insert and update etc in the database. Is it possible to use a single transaction for all these called methods? Like:

private void method_A(){/* doing tons of db stuff.. */}
private void method_B(){/*..*/}
private void method_C(){/*..*/}


protected void Insert_OnClick(object sender, EventArgs e)
{
    //begin transaction

    Method_A();

    Method_B();

    Method_C();

    //end transaction

}

Is this way possible? Never used transaction before. Btw using MS Access db if that matters.

Upvotes: 2

Views: 743

Answers (1)

Andrew Kilburn
Andrew Kilburn

Reputation: 2251

    using (OleDbConnection connection =
                   new OleDbConnection(connectionString))
        {
            OleDbCommand command = new OleDbCommand();
            OleDbTransaction transaction = null;

            // Set the Connection to the new OleDbConnection.
            command.Connection = connection;

            // Open the connection and execute the transaction.
            try
            {
                connection.Open();
                transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
  transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);

            // Assign transaction object for a pending local transaction.
            command.Connection = connection;
            command.Transaction = transaction;

                Method1(command.connection);
                Method2(command.connection);

            }
    }

Something like that?

So you using one connection and then set the transaction level and run your methods.

See here for more info: https://msdn.microsoft.com/en-us/library/93ehy0z8(v=vs.110).aspx

Upvotes: 1

Related Questions