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

如果不再需要某些对象,则可以将这些对象从对象上下文中分离。 为此,请调用 Detach 方法。 此时将减少所占用的内存量。

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

本主题中的示例基于 Adventure Works 销售模型。 若要运行本示例中的代码,必须已将 AdventureWorks 销售模型添加到您的项目中,并将项目配置为使用实体框架。 为此,请完成如何:手动配置实体框架项目如何:手动定义模型和映射文件(实体框架) 中的过程。

示例

本示例说明当应用程序不再需要 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.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());
    }
}

另请参见

概念

管理连接和事务(实体框架)
使用对象(实体框架)