Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use transaction through multiple layer code in C#

Suppose my project is like .net petshop. It has a BLL, DAL and SQLHelper.

Normally, I call a BLL function in my web layer, and the BLL function calls the DAL function and finally, the DAL call the sqlhelper.

But in some situations, I nedd a transaction.

For example:

Web layer:

I need Call some BLL functions. Code as below:

var m = BLLFunction_1();

var n=  BLLFunction_2();

if (m+n<100)
{
// need rollback here
}
else
{
BLLFunction_3();
// commit here 
}

So it makes me have to use a transaction object in the web layer, to pass it into the BLL function, and BLL layer pass it into DAL layer, and finally pass it into SQLHelper.

That's a little ugly.

I wonder what is a elegant methed to this situation.

like image 507
roast_soul Avatar asked Feb 26 '26 02:02

roast_soul


1 Answers

I am assuming you are looking for Transaction in ADO.NET.

Basically you need to wrap your "actions" into a TransactionScope.

    try
    {
        using(TransactionScope ts = new TransactionScope())
        {
            //perform SQL
            using(SqlHelper sh = new SqlHelper())
            {
                //do stuff
            }

            //call new DAL function

            //call other DAL function

            ts.Complete();            
        }
    }
    catch(Exception ex)
    {
        throw ex;
    }
like image 82
Levi Kovacs Avatar answered Feb 27 '26 18:02

Levi Kovacs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!