Share via


How to: Bracket Data Submissions by Using Transactions (LINQ to SQL)

You can use TransactionScope to bracket your submissions to the database. For more information, see Transactions (LINQ to SQL).

Example

The following code encloses the database submission in a TransactionScope.

        Dim db As New Northwnd("c:\northwnd.mdf")
        Using ts = New TransactionScope()
            Try

                Dim prod1 = db.Products.First(Function(p) p.ProductID = 4)
                Dim prod2 = db.Products.First(Function(p) p.ProductID = 5)
                prod1.UnitsInStock -= 3
                prod2.UnitsInStock -= 5
                db.SubmitChanges()
        ts.Complete()

            Catch e As Exception
                Console.WriteLine(e.Message)
            End Try
        End Using
            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);
                }
            }

See Also

Concepts

Downloading Sample Databases (LINQ to SQL)

Transactions (LINQ to SQL)

Other Resources

Making and Submitting Data Changes (LINQ to SQL)