ObjectContext.SaveChanges ObjectContext.SaveChanges ObjectContext.SaveChanges ObjectContext.SaveChanges Method

Definition

Persists all updates to the data source.

Overloads

SaveChanges() SaveChanges() SaveChanges() SaveChanges()

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

SaveChanges(Boolean) SaveChanges(Boolean) SaveChanges(Boolean) SaveChanges(Boolean)

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

SaveChanges(SaveOptions) SaveChanges(SaveOptions) SaveChanges(SaveOptions) SaveChanges(SaveOptions)

Persists all updates to the data source with the specified SaveOptions.

SaveChanges() SaveChanges() SaveChanges() SaveChanges()

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

public:
 int SaveChanges();
public int SaveChanges ();
member this.SaveChanges : unit -> int
Public Function SaveChanges () As Integer

Returns

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

Exceptions

Examples

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())
{
    try
    {
        // Perform an operation with a high-level of concurrency.
        // Change the status of all orders without an approval code.
        ObjectQuery<SalesOrderHeader> orders =
            context.SalesOrderHeaders.Where(
            "it.CreditCardApprovalCode IS NULL").Top("100");

        foreach (SalesOrderHeader order in orders)
        {
            // Reset the order status to 4 = Rejected.
            order.Status = 4;
        }
        try
        {
            // 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.
            context.SaveChanges();
            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)
    {
        Console.WriteLine(ex.ToString());
    }
}
Using context As New AdventureWorksEntities()
    Try
        ' Perform an operation with a high-level of concurrency. 
        ' Change the status of all orders without an approval code. 
        Dim orders As ObjectQuery(Of SalesOrderHeader) = context.SalesOrderHeaders.Where("it.CreditCardApprovalCode IS NULL").Top("100")

        For Each order As SalesOrderHeader In orders
            ' Reset the order status to 4 = Rejected. 
            order.Status = 4
        Next
        Try
            ' Try to save changes, which may cause a conflict. 
            Dim num As Integer = context.SaveChanges()
            Console.WriteLine("No conflicts. " & num.ToString() & " updates saved.")
        Catch generatedExceptionName As OptimisticConcurrencyException
            ' Resolve the concurrency conflict by refreshing the 
            ' object context before re-saving changes. 
            context.Refresh(RefreshMode.ClientWins, orders)

            ' Save changes. 
            context.SaveChanges()
            Console.WriteLine("OptimisticConcurrencyException handled and changes saved")
        End Try

        For Each order As SalesOrderHeader In orders
            Console.WriteLine(("Order ID: " & order.SalesOrderID.ToString() & " Order status: ") + order.Status.ToString())
        Next
    Catch ex As UpdateException
        Console.WriteLine(ex.ToString())
    End Try
End Using

Remarks

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.

See Also

SaveChanges(Boolean) SaveChanges(Boolean) SaveChanges(Boolean) SaveChanges(Boolean)

Warning

This API is now obsolete.

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

public:
 int SaveChanges(bool acceptChangesDuringSave);
[System.ComponentModel.Browsable(false)]
[System.Obsolete("Use SaveChanges(SaveOptions options) instead.")]
public int SaveChanges (bool acceptChangesDuringSave);
member this.SaveChanges : bool -> int
Public Function SaveChanges (acceptChangesDuringSave As Boolean) As Integer

Parameters

acceptChangesDuringSave
Boolean Boolean Boolean Boolean

This parameter is needed for client-side transaction support. If true, the change tracking on all objects is reset after SaveChanges(Boolean) finishes. If false, you must call the AcceptAllChanges() method after SaveChanges(Boolean).

Returns

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

Exceptions

Remarks

Call the SaveChanges(SaveOptions) method instead.

SaveChanges(SaveOptions) SaveChanges(SaveOptions) SaveChanges(SaveOptions) SaveChanges(SaveOptions)

Persists all updates to the data source with the specified SaveOptions.

public:
 virtual int SaveChanges(System::Data::Objects::SaveOptions options);
public virtual int SaveChanges (System.Data.Objects.SaveOptions options);
abstract member SaveChanges : System.Data.Objects.SaveOptions -> int
override this.SaveChanges : System.Data.Objects.SaveOptions -> int
Public Overridable Function SaveChanges (options As SaveOptions) As Integer

Parameters

options
SaveOptions SaveOptions SaveOptions SaveOptions

A SaveOptions value that determines the behavior of the operation.

Returns

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

Exceptions

Remarks

Use this specific overload of SaveChanges to either make sure that DetectChanges is called before you save changes to the data source or that AcceptAllChanges is called after you save changes to the data source.

This enumeration has a FlagsAttribute that allows for a bitwise combination of its member values.

To make sure 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. The SaveChanges method operates in a transaction. SaveChanges will roll back that transaction and throw an exception if any one 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 values, and then calling the SaveChanges method again. For more information, see How to: Manage Data Concurrency in the Object Context.

Applies to