How to: Bracket Data Submissions by Using Transactions

 

You can use TransactionScope to bracket your submissions to the database. For more information, see Transaction Support.

The following code encloses the database submission in a TransactionScope.

            Northwnd db = new Northwnd(@"c:\northwnd.mdf");
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    Product prod1 = db.Products.First(p => p.ProductID == 4);
                    Product prod2 = db.Products.First(p => p.ProductID == 5);
                    prod1.UnitsInStock -= 3;
                    prod2.UnitsInStock -= 5;
                    db.SubmitChanges();
		    ts.Complete();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

Downloading Sample Databases
Making and Submitting Data Changes
Transaction Support

Show: