Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
i want to implement sql transactions in my three tier architecture but don't know how to do. stuck from three days not seen any example i searched every where. my Basic need is that i want to save records in two different tables. using begin tran, commit and roll back trans.Any example should be preferred Thanks in advance.
Posted
Updated 16-Oct-14 22:00pm
v2

Transactions should only be implemented in the data layer, do not include business layers or heaven forbid UI layers in it.

SqlTransaction Class[^]
 
Share this answer
 
Yes. You can use sqltransaction in your data access layer.

Please refer this article in Code Project and if you still need any help, please reply and I'll assist you accordingly.

Using Transactions in ADO.NET
 
Share this answer
 
 
Share this answer
 
 
Share this answer
 
protected void btnSumbit_Click(object sender, EventArgs e)
{
//Begin Transaction
string conn = ConfigurationManager.AppSettings["YourConnectionString"];
SqlConnection objConnection = new SqlConnection(conn);
SqlTransaction trans = objConnection.BeginTransaction();
try
{


InsertData(ref trans, objConnection);
//Do Multiple Operations
trans.Commit();
}
catch
{

//Rollback Transaction
trans.Rollback();
}



}
private void InsertData(ref SqlTransaction trans, SqlConnection objConnection)
{
//Delete Product
SqlCommand cmd = new SqlCommand("Delete From Table Where ID=1", objConnection, trans);

cmd.ExecuteNonQuery();
}


//Put InsertData function in any Tier
www.learnlogic.blogspot.com
 
Share this answer
 
Ok 3 Tier.....

Ok I'd create a method in my data access layer which creates and adds a transaction to my current connection.

Then I would call this through my BusinessLogic when Inserting and Updating my records. So I would have a class in BusinessLogic SystemMethods, or something to that affect.

Then wherever I am doing my processing I would just call using(DbTransaction _trans = SystemMethods.CreateTransaction())
{
try
{
//add here
_trans.Commit();
}
catch(Exception ex)
{
_trans.Rollback();
}

}

hope that helps......
 
Share this answer
 
/Begin Transaction
SqlTransaction trans = conn.BeginTransaction("RemoveProducts");


//Delete Product
SqlCommand cmd = new SqlCommand("", conn, trans);
cmd.CommandText = "Delete from Products where ID=5";
cmd.ExecuteNonQuery();


//Save Transaction
trans.Save("ProductRemoved");

//Delete another product
cmd.CommandText = "Delete from Products where ID=13";
cmd.ExecuteNonQuery();

//Rollback Transaction to Save Point
trans.Rollback("ProductRemoved");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900