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

定義

將所有更新保存至資料來源。Persists all updates to the data source.

多載

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)

使用指定的 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

傳回

呼叫 Added 時處於 ModifiedDeletedSaveChanges() 狀態的物件數目。The number of objects in an Added, Modified, or Deleted state when SaveChanges() was called.

例外狀況

在資料來源中已經發生開放式並行存取 (Optimistic Concurrency) 違規。An optimistic concurrency violation has occurred in the data source.

範例

這個範例根據AdventureWorks Sales ModelThis 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

備註

若要確保用戶端的物件已經由資料來源端邏輯所更新,您可以在呼叫 Refresh 之後,使用 StoreWins 值來呼叫 SaveChanges 方法。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 在交易內運作。SaveChanges operates within a transaction. SaveChanges 將會復原該筆交易並擲回例外狀況,如果任何已變更ObjectStateEntry無法保存物件。SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted.

如果已經發生開放式並行存取違規,就會擲回 OptimisticConcurrencyExceptionIf an optimistic concurrency violation has occurred, an OptimisticConcurrencyException is thrown. 您可以透過攔截開放式並行存取違規、使用 RefreshStoreWins 值來呼叫 ClientWins 方法,然後再次呼叫 SaveChanges,解決開放式並行存取違規。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.

另請參閱

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

警告

此 API 現已淘汰。

將所有更新保存至資料來源,並且選擇性地重設物件內容中的變更追蹤。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

參數

acceptChangesDuringSave
Boolean Boolean Boolean Boolean

用戶端交易支援需要這個參數。This parameter is needed for client-side transaction support. 如果為 true,就會在 SaveChanges(Boolean) 完成之後,重設所有物件的變更追蹤。If true, the change tracking on all objects is reset after SaveChanges(Boolean) finishes. 如果為 false,您就必須在 AcceptAllChanges() 之後呼叫 SaveChanges(Boolean) 方法。If false, you must call the AcceptAllChanges() method after SaveChanges(Boolean).

傳回

呼叫 Added 時處於 ModifiedDeletedSaveChanges() 狀態的物件數目。The number of objects in an Added, Modified, or Deleted state when SaveChanges() was called.

例外狀況

已經發生開放式並行存取違規。An optimistic concurrency violation has occurred.

備註

呼叫SaveChanges(SaveOptions)方法改為。Call the SaveChanges(SaveOptions) method instead.

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

使用指定的 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

參數

options
SaveOptions SaveOptions SaveOptions SaveOptions

決定作業行為的 SaveOptions 值。A SaveOptions value that determines the behavior of the operation.

傳回

呼叫 Added 時處於 ModifiedDeletedSaveChanges() 狀態的物件數目。The number of objects in an Added, Modified, or Deleted state when SaveChanges() was called.

例外狀況

已經發生開放式並行存取違規。An optimistic concurrency violation has occurred.

備註

使用這個特定的多載SaveChanges,請先確定DetectChanges之前,您將變更儲存至資料來源或是呼叫AcceptAllChanges之後您將變更儲存至資料來源會呼叫。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.

此列舉具有FlagsAttribute,允許其成員值的位元組合。This enumeration has a FlagsAttribute that allows for a bitwise combination of its member values.

若要確定用戶端的物件,已由資料來源端邏輯所更新,您可以呼叫Refresh方法StoreWins值之後呼叫SaveChangesTo 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. SaveChanges方法會在交易中運作。The SaveChanges method operates in a transaction. SaveChanges 將會復原該筆交易並擲回例外狀況,如果任何一個已變更ObjectStateEntry無法保存物件。SaveChanges will roll back that transaction and throw an exception if any one of the dirty ObjectStateEntry objects cannot be persisted.

如果已經發生開放式並行存取違規,就會擲回 OptimisticConcurrencyExceptionIf an optimistic concurrency violation has occurred, an OptimisticConcurrencyException is thrown. 您可以透過攔截開放式並行存取違規、使用 RefreshStoreWins 值來呼叫 ClientWins 方法,然後再次呼叫 SaveChanges 方法,解決開放式並行存取違規。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.

適用於