HOW TO:從物件內容中斷物件的連結 (Entity Framework)

當您不再需要物件時,物件服務可讓您從物件內容中斷物件的連結。執行的方式是呼叫 Detach 方法。這樣會減少使用的記憶體數量。

雖然中斷物件連結確實有好處,但是也應該要考量執行此作業所需的額外處理。如需詳細資訊,請參閱中斷連結物件 (Entity Framework)

本主題的範例是根據 Adventure Works Sales Model。若要執行此範例中的程式碼,您必須已經將 AdventureWorks Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。若要這樣做,請完成 HOW TO:手動設定 Entity Framework 專案HOW TO:以手動方式定義 Entity Data Model (Entity Framework) 中的程序。

範例

此範例會示範如何在應用程式不再需要 SalesOrderDetailSalesOrderHeader 物件時,從 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.SalesOrderDetail.Count > 0
            ' Detach the first SalesOrderDetail in the collection.
            context.Detach(order.SalesOrderDetail.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.SalesOrderDetail.Count > 0)
        {
            // Detach the first SalesOrderDetail in the collection.
            context.Detach(order.SalesOrderDetail.First());
        }

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

另請參閱

概念

在物件服務中管理資源 (Entity Framework)

其他資源

管理物件內容 (Entity Framework)
使用物件 (Entity Framework 工作)