Edit

Share via


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.

Example

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);
    }
}
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

See also