Share via


オブジェクト コンテキストから接続を手動で開く方法 (Entity Framework)

このトピックでは、オブジェクト コンテキストから接続を手動で開く方法について説明します。詳細については、「オブジェクト コンテキストの管理 (Entity Framework)」を参照してください。

このトピックの例には、AdventureWorks Sales Model (EDM) が使用されています。この例のコードを実行するには、あらかじめプロジェクトに AdventureWorks Sales Model を追加し、Entity Framework を使用するようにプロジェクトを構成しておく必要があります。具体的な方法については、「Entity Data Model ウィザードを使用する方法 (Entity Framework)」の手順を参照してください。

この例では、接続を手動で開いた後、クエリを実行し、変更を保存します。コンテキストがスコープ外になり、破棄されたときに、接続が閉じられます。

' Define the order ID for the order we want.
Dim orderId As Integer = 43661

Using advWorksContext As New AdventureWorksEntities()
    Try
        ' Explicitly open the connection.
        advWorksContext.Connection.Open()

        ' Execute a query to return an order.
        Dim order As SalesOrderHeader = _
            advWorksContext.SalesOrderHeader.Where( _
            "it.SalesOrderID = @orderId", New ObjectParameter("orderId", orderId)) _
            .Execute(MergeOption.AppendOnly).First()

        ' Change the status of the order.
        order.Status = 1

        ' Save changes.
        If 0 < advWorksContext.SaveChanges() Then
        Console.WriteLine("Changes saved.")
        End If
    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
    ' The connection is closed when the object context
    ' is disposed because it is no longer in scope.
End Using
// Define the order ID for the order we want.
int orderId = 43661;

using (AdventureWorksEntities advWorksContext =
    new AdventureWorksEntities())
{
    try
    {
        // Explicitly open the connection.    
        advWorksContext.Connection.Open();

        // Execute a query to return an order.
        SalesOrderHeader order =
            advWorksContext.SalesOrderHeader.Where(
            "it.SalesOrderID = @orderId", new ObjectParameter("orderId", orderId))
            .Execute(MergeOption.AppendOnly).First();


        // Change the status of the order.
        order.Status = 1;

        // Save changes.
        if (0 < advWorksContext.SaveChanges())
        {
            Console.WriteLine("Changes saved.");
        }
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }

    // The connection is closed when the object context
    // is disposed because it is no longer in scope.
}

参照

処理手順

実行時間の長いオブジェクト コンテキストの接続を管理する方法 (Entity Framework)
オブジェクト コンテキストで EntityConnection を使用する方法 (Entity Framework)