方法: データ送信をトランザクションで囲むHow to: Bracket Data Submissions by Using Transactions

データベースへの送信を TransactionScope で囲むことができます。You can use TransactionScope to bracket your submissions to the database. 詳細については、次を参照してください。トランザクション サポートします。For more information, see Transaction Support.

Example

次のコードでは、データベース送信を TransactionScope で囲みます。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