SaveChanges Method
Collapse the table of content
Expand the table of content

ObjectContext.SaveChanges Method ()


Persists all updates to the data source and resets change tracking in the object context.

Namespace:   System.Data.Objects
Assembly:  System.Data.Entity (in System.Data.Entity.dll)

public int SaveChanges()

Return Value

Type: System.Int32

The number of objects in an Added, Modified, or Deleted state when SaveChanges was called.

Exception Condition

An optimistic concurrency violation has occurred in the data source.

To ensure that objects on the client have been updated by data source-side logic, you can call the Refresh method with the StoreWins value after you call SaveChanges. For more information, see Saving Changes and Managing Concurrency.

SaveChanges operates within a transaction. SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted.

If an optimistic concurrency violation has occurred, an OptimisticConcurrencyException is thrown. You can resolve an optimistic concurrency violation by catching it, calling the Refresh method with the StoreWins or ClientWins value, and then calling SaveChanges again. For more information, see How to: Manage Data Concurrency in the Object Context.

This example is based on the AdventureWorks Sales Model. This example tries to save changes, which may cause a concurrency conflict. Then, it demonstrates how to resolve the concurrency conflict by refreshing the object context before re-saving changes.

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
        // Perform an operation with a high-level of concurrency.
        // Change the status of all orders without an approval code.
        ObjectQuery<SalesOrderHeader> orders =
            "it.CreditCardApprovalCode IS NULL").Top("100");

        foreach (SalesOrderHeader order in orders)
            // Reset the order status to 4 = Rejected.
            order.Status = 4;
            // Try to save changes, which may cause a conflict.
            int num = context.SaveChanges();
            Console.WriteLine("No conflicts. " +
                num.ToString() + " updates saved.");
        catch (OptimisticConcurrencyException)
            // Resolve the concurrency conflict by refreshing the 
            // object context before re-saving changes. 
            context.Refresh(RefreshMode.ClientWins, orders);

            // Save changes.
            Console.WriteLine("OptimisticConcurrencyException "
            + "handled and changes saved");

        foreach (SalesOrderHeader order in orders)
            Console.WriteLine("Order ID: " + order.SalesOrderID.ToString()
                + " Order status: " + order.Status.ToString());
    catch (UpdateException ex)

.NET Framework
Available since 3.5
Return to top
© 2015 Microsoft