How to: Detach Objects from an Object Context (Entity Framework)

Object Services enables you to detach objects from an object context when they are no longer required. To do this, call the Detach method. This reduces the amount of memory used.

The benefits of detaching objects should be considered against the additional processing required to perform the operation. For more information, see Detaching Objects (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 How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework).

Example

This example shows how to detach SalesOrderDetail and SalesOrderHeader objects from an ObjectContext when they are no longer required by the application.

' 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());
    }
}

See Also

Concepts

Managing Resources in Object Services (Entity Framework)

Other Resources

Managing the Object Context (Entity Framework)
Working with Objects (Entity Framework Tasks)