Cómo aplicar los cambios realizados a un objeto desasociado (Entity Framework)

En este tema, se proporciona un ejemplo de cómo aplicar a un objeto las actualizaciones llevadas a cabo en una instancia desasociada del mismo objeto. Este procedimiento se usa cuando un objeto se actualiza desde una ubicación remota y se restablece en el servidor para conservar los cambios. Si el objeto simplemente estuviera asociado a un contexto del objeto en el servidor, las actualizaciones se perderían, o bien se produciría un error en la operación si el objeto ya estuviera en el contexto del objeto. Esto sucede porque los objetos se asocian en un estado Unchanged. Para obtener más información, vea Asociar y desasociar objetos (Entity Framework).

El ejemplo de este tema se basa en el modelo Adventure Works Sales. Para ejecutar el código de este ejemplo, debe haber agregado ya el modelo AdventureWorks Sales al proyecto y haber configurado el proyecto para que use Entity Framework. Para ello, complete los procedimientos de Cómo configurar manualmente un proyecto de Entity Framework y Cómo: Definir manualmente los archivos de asignación y modelo (Entity Framework).

Ejemplo

En el ejemplo siguiente, se pasa un objeto SalesOrderDetail actualizado al método UpdateItemChanges, junto con el objeto original. Esto permite aplicar los cambios sin consultar el objeto y sin tener que conservarlo en la memoria. También puede recuperar el objeto original de la base de datos en lugar de exigir al cliente que lo pase.

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

Vea también

Conceptos

Crear aplicaciones de n niveles (Entity Framework)
Serializar objetos (Entity Framework)
Asociar y desasociar objetos (Entity Framework)
Trabajar con objetos (Entity Framework)