Wednesday, December 26, 2012

How to handle Transactions in LINQ


I was recently developing an application in LINQ and needed to find a way to handle transactions when updating the database.

I used TransactionScope class for that purpose. You need to add the "using System.Transactions;" reference.

Below is a example usage.

public string InsertBrand(MobileBrand brand)

        {
            try
            {
                airTouch = new AirTouchDataContext(ConString.DBConnection);
                using (TransactionScope transaction = new TransactionScope())
                {
                    tblMobileBrand tblbrand = new tblMobileBrand();
                    tblbrand.BrandName = brand.BrandName;
                    tblbrand.AddedBy = brand.AddedBy;
                    tblbrand.TimeStamp = DateTime.ParseExact(DateTime.Now.ToShortDateString(), "dd/MM/yyyy", DateTimeFormatInfo.InvariantInfo);
                    airTouch.tblMobileBrands.InsertOnSubmit(tblbrand);
                    airTouch.SubmitChanges();
                    transaction.Complete();
                    return "Mobile Brand Added";

                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

No comments:
Write comments
Recommended Posts × +