オブジェクト コンテキストからオブジェクトをデタッチする方法 (Entity Framework)

不要になったオブジェクトをオブジェクト コンテキストからデタッチすることができます。 それには、Detach メソッドを呼び出します。 これにより、使用メモリの量が削減されます。

操作を実行するために追加の処理が必要な場合は、オブジェクトのデタッチを検討する必要があります。 詳細については、「オブジェクトのアタッチとデタッチ (Entity Framework)」を参照してください。

The example in this topic is based on the Adventure Works Sales Model. To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in Entity Framework プロジェクトを手動で構成する方法 and 方法: モデル ファイルとマッピング ファイルを手動で定義する (Entity Framework).

この例では、アプリケーションで不要になった SalesOrderDetail オブジェクトと SalesOrderHeader オブジェクトを ObjectContext からデタッチする方法を示します。

' This method is called to detach SalesOrderHeader objects and 
' related SalesOrderDetail objects from the supplied object 
' context when no longer needed by the application. 
' Once detached, the resources can be garbage collected. 
Private Shared Sub DetachOrders(ByVal context As ObjectContext, ByVal order As SalesOrderHeader)
    Try
        ' Detach each item from the collection. 
        While order.SalesOrderDetails.Count > 0
            ' Detach the first SalesOrderDetail in the collection. 
            context.Detach(order.SalesOrderDetails.First())
        End While

        ' Detach the order. 
        context.Detach(order)
    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
End Sub
// This method is called to detach SalesOrderHeader objects and 
// related SalesOrderDetail objects from the supplied object
// context when no longer needed by the application. 
// Once detached, the resources can be garbage collected.
private static void DetachOrders(ObjectContext context,
    SalesOrderHeader order)
{
    try
    {
        // Detach each item from the collection.
        while (order.SalesOrderDetails.Count > 0)
        {
            // Detach the first SalesOrderDetail in the collection.
            context.Detach(order.SalesOrderDetails.First());
        }

        // Detach the order.
        context.Detach(order);
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

参照

概念

接続とトランザクションの管理 (Entity Framework)
オブジェクトの使用 (Entity Framework)