如何:从对象上下文分离对象(实体框架)

借助于对象服务,当不再需要某些对象时,您可以从对象上下文中分离这些对象。为此,请调用 Detach 方法。此时将减少所占用的内存量。

应对照执行分离操作时所需要的附加处理量来考察分离对象所带来的优势。有关更多信息,请参见分离对象(实体框架)

本主题中的示例基于 Adventure Works 销售模型。若要运行本示例中的代码,必须已将 AdventureWorks 销售模型添加到您的项目中,并将项目配置为使用 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());
    }
}

另请参见

概念

在对象服务中管理资源(实体框架)

其他资源

管理对象上下文(实体框架)
使用对象(实体框架任务)