I would like to ask how to run at least two updates under one transaction. When one of them fails transaction is rolled back. My update functions now look like this. Basically I start new connection, create sql statement and assign it a transaction, run statement and then commit or rollback. Try/catch blocks are not included yet.
public int UpdateCategory(string categoryId, string title, int price)
{
var db = new DB(); //Class that handles operations on DB
db.Connect(); //Connection open
/* I do not want to post whole DB class but it does this and return new Sql statment */
var conn = db.GetConnection();
var tran = conn.BeginTransaction(IsolationLevel.ReadCommitted);
string query = "update ...";
SqlCommand command = new SqlCommand(query, conn, tran );
int row = db.ExecuteNonQuery(command);
if (row == 1)
{
tran.Commit();
return 1;
}
tran.Rollback();
return 0;
}
My application uses 3 layers DAL (table data gateway), BLL (transaction script), PL. So far I came with this:
- From one update method call another one which is placed in different gateway, so they can easily share transaction
- At BLL create new connection and transaction and pass it as a parameter into update methods. Commit or rollback in BLL
- Having some "global" connection still opened and used for all operations in application and closed when app is closed.
I don't like first one since table data gateways should be concerned only about one table. It would be easy but messy I think. Second one is not that good because I would like to keep all db access at my DAL and not using it BLL. Third is just ugly and maybe not doable.
Do you have any suggestions how to make this happen in a clean way? + Does commit() and rollback() disconnect the opened connection?
Aucun commentaire:
Enregistrer un commentaire