.NET Framework Class Library
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)
Syntax

Visual Basic (Declaration)
Public Function SaveChanges As Integer
Visual Basic (Usage)
Dim instance As ObjectContext
Dim returnValue As Integer

returnValue = instance.SaveChanges()
C#
public int SaveChanges()
Visual C++
public:
int SaveChanges()
JScript
public function SaveChanges() : int

Return Value

Type: System..::.Int32
The number of objects in an Added, Modified, or Deleted state when SaveChanges was called.
Exceptions

ExceptionCondition
InvalidOperationException

The service adapter is nullNothingnullptra null reference (Nothing in Visual Basic).

OptimisticConcurrencyException

An optimistic concurrency violation has occurred in the data source.

Remarks

This method is to the same as calling SaveChanges(Boolean) and passing a value of true.

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 (Entity Framework).

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 (Entity Framework).

Examples

This example is based on the Adventure Works 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.

Visual Basic
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.SalesOrderHeader.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 ex 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
C#
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.SalesOrderHeader.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());
    }
}
Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5 SP1
See Also

Reference

Other Resources

Tags :


Community Content

Shimmy Weitzhandler
Items are flushen on new added item after SaveChanges
Please take a look and share your ideas:
http://stackoverflow.com/questions/1119168/when-calling-objectcontext-savechanges-added-entities-are-cleared
Tags :

Shimmy Weitzhandler
Items are flushed when adding a new item after SaveChanges is called.
Please take a look and share your ideas:
http://stackoverflow.com/questions/1119168/when-calling-objectcontext-savechanges-added-entities-are-cleared

Page view tracker