HOW TO:從物件內容中斷物件的連結 (Entity Framework)
當您不再需要物件時,便可以從物件內容中斷物件的連結。 執行的方式是呼叫 Detach 方法。 這樣會減少使用的記憶體數量。
雖然中斷物件連結確實有好處,但是也應該要考量執行此作業所需的額外處理。 如需詳細資訊,請參閱附加及中斷連結物件。
本主題的範例是根據 Adventure Works Sales Model。 若要執行此範例中的程式碼,您必須已經將 AdventureWorks Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。 若要這樣做,請完成 HOW TO:手動設定 Entity Framework 專案和 HOW TO:手動定義模型和對應檔 (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());
}
}