방법: 개체 컨텍스트에서 개체 분리(Entity Framework)

더 이상 필요하지 않은 개체를 개체 컨텍스트에서 분리할 수 있습니다. 이렇게 하려면 Detach 메서드를 호출합니다. 개체 컨텍스트에서 개체를 분리하면 메모리 사용량이 줄어듭니다.

개체 분리 작업을 수행하는 데 필요한 추가 작업과 비교하여 개체 분리를 통해 얻을 수 있는 장점을 고려해야 합니다. 자세한 내용은 개체 연결 및 분리(Entity Framework)를 참조하십시오.

이 항목의 예제는 Adventure Works Sales 모델을 기반으로 합니다. 이 예제의 코드를 실행하려면 프로젝트에 AdventureWorks Sales 모델을 추가하고 Entity Framework를 사용하도록 프로젝트를 구성해야 합니다. 이렇게 하려면 방법: Entity Framework 프로젝트 수동 구성방법: 수동으로 모델 및 매핑 파일 정의(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.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());
    }
}

참고 항목

개념

연결 및 트랜잭션 관리(Entity Framework)
개체 사용(Entity Framework)