방법: 분리된 개체에 대한 변경 내용 적용(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 context As New AdventureWorksEntities()
        context.SalesOrderDetails.Attach(updatedItem)
        ' Check if the ID is 0, if it is the item is new. 
        ' In this case we need to chage the state to Added. 
        If updatedItem.SalesOrderDetailID = 0 Then
            ' Because the ID is generated by the database we do not need to 
            ' set updatedItem.SalesOrderDetailID. 
            context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added)
        Else
            ' If the SalesOrderDetailID is not 0, then the item is not new 
            ' and needs to be updated. Because we already added the 
            ' updated object to the context we need to apply the original values. 
            ' If we attached originalItem to the context 
            ' we would need to apply the current values: 
            ' context.ApplyCurrentValues("SalesOrderDetails", updatedItem); 
            ' Applying current or original values, changes the state 
            ' of the attached object to Modified. 
            context.ApplyOriginalValues("SalesOrderDetails", originalItem)
        End If
        context.SaveChanges()
    End Using
End Sub
private static void ApplyItemUpdates(SalesOrderDetail originalItem,
    SalesOrderDetail updatedItem)
{
    using (AdventureWorksEntities context =
        new AdventureWorksEntities())
    {
        context.SalesOrderDetails.Attach(updatedItem);
        // Check if the ID is 0, if it is the item is new. 
        // In this case we need to chage the state to Added.
        if (updatedItem.SalesOrderDetailID == 0)
        {
            // Because the ID is generated by the database we do not need to
            // set updatedItem.SalesOrderDetailID.
            context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added);
        }
        else
        {
            // If the SalesOrderDetailID is not 0, then the item is not new
            // and needs to be updated. Because we already added the 
            // updated object to the context we need to apply the original values.
            // If we attached originalItem to the context 
            // we would need to apply the current values:
            // context.ApplyCurrentValues("SalesOrderDetails", updatedItem);
            // Applying current or original values, changes the state 
            // of the attached object to Modified.
            context.ApplyOriginalValues("SalesOrderDetails", originalItem);
        }
        context.SaveChanges();
    }
}

참고 항목

개념

n 계층 응용 프로그램 작성(Entity Framework)
개체 Serialize(Entity Framework)
개체 연결 및 분리(Entity Framework)
개체 사용(Entity Framework)