Click here to Skip to main content
15,896,469 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Any one can give me link OR Suggest me... How to use transaction and commit in three tier asp.net architecture. And on which layer i can use transaction and commit for multiple insert QUERY ..
Posted

Transactions should be kept in the same layer as the database access, i.e. the Data Access layer (DAL)

I use a TransactionScope wrapper for all of my transactions:

C#
public delegate void Transaction();

private const int Retries = 3;

public static void TransactionWrapper(Transaction transaction)
{
    var options = new TransactionOptions
    {
        IsolationLevel = IsolationLevel.Snapshot,
        Timeout = TimeSpan.FromSeconds(120)
    };

    for (int x = 0; x < Retries; x++)
    {
        try
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Required, options))
            {
                transaction();

                scope.Complete();

            }

            x = Retries;
        }
        catch (Exception exception)
        {
            //Exception loggedException = new Exception(string.Format("Transaction attempt {0} fail", x), exception);
            //Logging.Logs.LogException(loggedException);
            if (x == Retries - 1)
                throw;
        }
    }
}


Which is used as follows:
C#
//create query
object result;
TransactionWrapper(()=>{
   result = //run the query
});

return result;



My code lends itself to creating all of the query cases on the DAL, including multiple transactions so I can add all of them in the wrapper at the same time.

I hope that helps ^_^
Andy
 
Share this answer
 
Comments
Enemali William 10-Sep-15 10:23am    
It is also advisable to use add an isolation level when you are running this to avoid
deadlocks
You can INSERT multiple records at once instead of inserting each time.

C#
string conStr=""; //Connection string
using (OleDbConnection con = new OleDbConnection(constr))
         {
             conStr.Open();
             var trans = con.BeginTransaction(); //Begin the transaction
             foreach (DataRow dr in dataTable.rows)
             {
                 //Read the data from datatable and insert
                 string query = ""; //Query

                 OleDbCommand cmd = new OleDbCommand(query, con);
                 cmd.Transaction = trans; //Assign transaction to oledb command
                 cmd.Parameters.AddWithValue("@Status", status);

                 cmd.ExecuteNonQuery();
             }
              trans.Commit(); //Committing transaction at once.
         }
 
Share this answer
 
v2

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