Reputation: 173
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(){/*...*/}
//etc
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: 1
Views: 4187
Reputation: 1332
Yes you could use a single transaction by creating an instance of the transaction and passing it into any method that would need to use it. Some psuedo-code to illustrate based on the code you've provided: A link as well: MSDN OleDbTransaction
protected void Insert_OnClick(object sender, EventArgs e)
{
//begin transaction
var connection = HoweverYoureManagingConnections();
using (var transaction = connection.BeginTransaction())//If using OleDb
{
try
{
var command = new OldDbCommand();
command.Transaction = transaction;
//Use passed in command object to issue your queries/inserts/updates in each method.
Method_A(command);
Method_B(command);
Method_C(command);
transaction.Commit();
}
catch(Exception ex)
{
//if there was an exception rollback.
transaction.Rollback();
}
}
}
Upvotes: 2
Reputation: 152596
Not certain if Access honors transactions but you can wrap the calls in a TransactionScope
. That implicitly adds all database activity within the scope to the transaction:
protected void Insert_OnClick(object sender, EventArgs e)
{
using(TransactionScope tran = new TransactionScope())
{
Method_A();
Method_B();
Method_C();
tran.Complete();
}
}
Upvotes: 4