How to: Apply Changes Made to a Detached Object
Collapse the table of content
Expand the table of content

How to: Apply Changes Made to a Detached Object

This topic provides an example of how to apply to an object updates made to a detached instance of the same object. This procedure is used when an object is updated remotely and set back to the server to persist the changes. If the object were simply attached to an object context at the server, updates would be lost or the operation would fail if the object was already in the object context. This occurs because objects are attached in an Unchanged state. For more information, see Attaching and Detaching Objects.

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 the Model and Mapping Files.


In the following example, an updated SalesOrderDetail object is passed to the UpdateItemChanges method, along with the original object. This enables changes to be applied without querying for the object or having to persist it in memory. You can also retrieve the original object from the database instead of requiring the client to pass it.

private static void ApplyItemUpdates(SalesOrderDetail originalItem,
    SalesOrderDetail updatedItem)
    using (AdventureWorksEntities context =
        new AdventureWorksEntities())
        // 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);
            // 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);

See Also

Community Additions

© 2016 Microsoft