방법: 분리된 개체에 대한 변경 내용 적용(Entity Framework)

이 항목에서는 동일 개체의 분리된 인스턴스에 대한 개체 업데이트를 적용하는 방법에 대한 예제를 제공합니다. 이 절차는 개체를 원격으로 업데이트하고 서버로 되돌려서 변경 내용을 유지할 때 사용됩니다. 개체가 단순히 서버의 개체 컨텍스트에 연결된 경우 업데이트가 손실되며, 개체가 이미 개체 컨텍스트에 있는 경우 작업이 실패할 수 있습니다. 이것은 Unchanged 상태에서 개체가 연결되기 때문입니다. 자세한 내용은 개체 연결(Entity Framework)을 참조하십시오.

이 항목의 예제는 Adventure Works Sales 모델을 기반으로 합니다. 이 예제의 코드를 실행하려면 프로젝트에 AdventureWorks Sales 모델을 추가하고 Entity Framework를 사용하도록 프로젝트를 구성해야 합니다. 이렇게 하려면 방법: Entity Framework 프로젝트 수동 구성방법: 엔터티 데이터 모델 수동 정의(Entity Framework)의 절차를 수행합니다.

예제

다음 예제에서 업데이트된 SalesOrderDetail 개체는 원래 개체와 함께 UpdateItemChanges 메서드에 전달됩니다. 이를 통해 개체를 쿼리하거나 메모리에 유지할 필요 없이 변경 내용을 적용할 수 있습니다.

Private Shared Sub ApplyItemUpdates(ByVal originalItem As SalesOrderDetail, _
    ByVal updatedItem As SalesOrderDetail)
    Using advWorksContext As AdventureWorksEntities = _
        New AdventureWorksEntities()
        Try

            ' Attach the original item to the object context.
            advWorksContext.Attach(originalItem)

            ' Call the ApplyPropertyChanges method to apply changes
            ' from the updated item to the original version.
            advWorksContext.ApplyPropertyChanges( _
                "SalesOrderDetail", updatedItem)

            advWorksContext.SaveChanges()

        Catch ex As InvalidOperationException
            Console.WriteLine(ex.ToString())
        End Try
    End Using
End Sub
private static void ApplyItemUpdates(SalesOrderDetail originalItem,
    SalesOrderDetail updatedItem)
{
    using (AdventureWorksEntities advWorksContext = 
        new AdventureWorksEntities())
    {
        try
        {
            // Attach the original item to the object context.
            advWorksContext.Attach(originalItem);

            // Call the ApplyPropertyChanges method to apply changes
            // from the updated item to the original version.
            advWorksContext.ApplyPropertyChanges("SalesOrderDetail",
                updatedItem);

            advWorksContext.SaveChanges();
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

이 예제에서는 원래 SalesOrderDetail 개체를 검색한 다음 UpdateItemChanges 메서드에 전달된 업데이트된 SalesOrderDetail 개체에 따라 변경 내용을 개체에 적용합니다.

Private Shared Sub ApplyItemUpdates(ByVal updatedItem As SalesOrderDetail)
    ' Define an ObjectStateEntry and EntityKey for the current object.
    Dim key As EntityKey
    Dim originalItem As Object

    Using advWorksContext As AdventureWorksEntities = _
        New AdventureWorksEntities()
        Try
            ' Create the detached object's entity key.
            key = advWorksContext.CreateEntityKey("SalesOrderDetail", updatedItem)

            ' Get the original item based on the entity key from the context
            ' or from the database.
            If advWorksContext.TryGetObjectByKey(key, originalItem) Then
                ' Call the ApplyPropertyChanges method to apply changes
                ' from the updated item to the original version.
                advWorksContext.ApplyPropertyChanges( _
                    key.EntitySetName, _
                    updatedItem)
            End If

            advWorksContext.SaveChanges()
        Catch ex As InvalidOperationException
            Console.WriteLine(ex.ToString())
        End Try

    End Using
End Sub
private static void ApplyItemUpdates(SalesOrderDetail updatedItem)
{
    // Define an ObjectStateEntry and EntityKey for the current object.
    EntityKey key;
    object originalItem;

    using (AdventureWorksEntities advWorksContext =
        new AdventureWorksEntities())
    {
        try
        {
            // Create the detached object's entity key.
            key = advWorksContext.CreateEntityKey("SalesOrderDetail", updatedItem);
            
            // Get the original item based on the entity key from the context
            // or from the database.
            if (advWorksContext.TryGetObjectByKey(key, out originalItem))
            {
                // Call the ApplyPropertyChanges method to apply changes
                // from the updated item to the original version.
                advWorksContext.ApplyPropertyChanges(
                    key.EntitySetName, updatedItem);
            }

            advWorksContext.SaveChanges();
        }
        catch (InvalidOperationException ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

참고 항목

개념

웹 서비스 및 엔터티 데이터 모델(응용 프로그램 시나리오)
개체 Serialize(Entity Framework)
개체 연결(Entity Framework)

기타 리소스

개체 사용(Entity Framework 작업)