ObjectContext.SaveChanges Método
Definição
Persiste todas as atualizações na fonte de dados.Persists all updates to the data source.
Sobrecargas
| SaveChanges() |
Persiste todas as atualizações na fonte de dados e redefine o controle de alterações no contexto de objeto.Persists all updates to the data source and resets change tracking in the object context. |
| SaveChanges(Boolean) |
Obsoleto.
Persiste todas as atualizações na fonte de dados e, opcionalmente, redefine o controle de alterações no contexto de objeto.Persists all updates to the data source and optionally resets change tracking in the object context. |
| SaveChanges(SaveOptions) |
Persiste todas as atualizações para a fonte de dados com o SaveOptions especificado.Persists all updates to the data source with the specified SaveOptions. |
SaveChanges()
Persiste todas as atualizações na fonte de dados e redefine o controle de alterações no contexto de objeto.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
Retornos
O número de objetos em um estado Added, Modified ou Deleted quando SaveChanges() foi chamado.The number of objects in an Added, Modified, or Deleted state when SaveChanges() was called.
Exceções
Ocorreu uma violação de simultaneidade otimista na fonte de dados.An optimistic concurrency violation has occurred in the data source.
Exemplos
Este exemplo é baseado no Microsoft SQL Server exemplos de produto: banco de dados.This example is based on the Microsoft SQL Server Product Samples: Database. Este exemplo tenta salvar as alterações, o que pode causar um conflito de simultaneidade.This example tries to save changes, which may cause a concurrency conflict. Em seguida, ele demonstra como resolver o conflito de simultaneidade atualizando o contexto do objeto antes de salvar as alterações novamente.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
Comentários
Para garantir que os objetos no cliente tenham sido atualizados pela lógica do lado da fonte de dados, você pode chamar o Refresh método com o StoreWins valor depois de chamar 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. Para obter mais informações, consulte salvando alterações e gerenciando a simultaneidade.For more information, see Saving Changes and Managing Concurrency.
SaveChanges Opera em uma transação.SaveChanges operates within a transaction. SaveChanges reverterá essa transação e lançará uma exceção se qualquer um dos objetos sujos ObjectStateEntry não puder persistir.SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted.
Se ocorrer uma violação de simultaneidade otimista, um OptimisticConcurrencyException será gerado.If an optimistic concurrency violation has occurred, an OptimisticConcurrencyException is thrown. Você pode resolver uma violação de simultaneidade otimista, capturando-a, chamando o Refresh método com o StoreWins ClientWins valor ou e, em seguida, chamando SaveChanges novamente.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. Para obter mais informações, consulte como: gerenciar a simultaneidade de dados no contexto do objeto.For more information, see How to: Manage Data Concurrency in the Object Context.
Aplica-se a
SaveChanges(Boolean)
Cuidado
Use SaveChanges(SaveOptions options) instead.
Persiste todas as atualizações na fonte de dados e, opcionalmente, redefine o controle de alterações no contexto de objeto.Persists all updates to the data source and optionally resets change tracking in the object context.
public:
int SaveChanges(bool acceptChangesDuringSave);
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
[<System.ComponentModel.Browsable(false)>]
[<System.Obsolete("Use SaveChanges(SaveOptions options) instead.")>]
member this.SaveChanges : bool -> int
Public Function SaveChanges (acceptChangesDuringSave As Boolean) As Integer
Parâmetros
- acceptChangesDuringSave
- Boolean
Esse parâmetro será necessário para suporte à transações do lado do cliente.This parameter is needed for client-side transaction support. Se for true, o controle de alterações em todos os objetos será redefinido após a conclusão do SaveChanges(Boolean).If true, the change tracking on all objects is reset after SaveChanges(Boolean) finishes. Se for false, você deverá chamar o método AcceptAllChanges() após SaveChanges(Boolean).If false, you must call the AcceptAllChanges() method after SaveChanges(Boolean).
Retornos
O número de objetos em um estado Added, Modified ou Deleted quando SaveChanges() foi chamado.The number of objects in an Added, Modified, or Deleted state when SaveChanges() was called.
- Atributos
Exceções
Ocorreu uma violação de simultaneidade otimista.An optimistic concurrency violation has occurred.
Comentários
SaveChanges(SaveOptions)Em vez disso, chame o método.Call the SaveChanges(SaveOptions) method instead.
Aplica-se a
SaveChanges(SaveOptions)
Persiste todas as atualizações para a fonte de dados com o SaveOptions especificado.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
Parâmetros
- options
- SaveOptions
Um valor SaveOptions que determina o comportamento da operação.A SaveOptions value that determines the behavior of the operation.
Retornos
O número de objetos em um estado Added, Modified ou Deleted quando SaveChanges() foi chamado.The number of objects in an Added, Modified, or Deleted state when SaveChanges() was called.
Exceções
Ocorreu uma violação de simultaneidade otimista.An optimistic concurrency violation has occurred.
Comentários
Use essa sobrecarga específica do SaveChanges para certificar-se de que DetectChanges é chamado antes de salvar as alterações na fonte de dados ou que AcceptAllChanges é chamado depois de salvar as alterações na fonte de dados.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.
Essa enumeração tem um FlagsAttribute que permite uma combinação de bit a bit de seus valores de membro.This enumeration has a FlagsAttribute that allows for a bitwise combination of its member values.
Para garantir que os objetos no cliente tenham sido atualizados pela lógica do lado da fonte de dados, você pode chamar o Refresh método com o StoreWins valor depois de chamar SaveChanges .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. O SaveChanges método opera em uma transação.The SaveChanges method operates in a transaction. SaveChanges reverterá essa transação e lançará uma exceção se qualquer um dos objetos sujos ObjectStateEntry não puder ser persistente.SaveChanges will roll back that transaction and throw an exception if any one of the dirty ObjectStateEntry objects cannot be persisted.
Se ocorrer uma violação de simultaneidade otimista, um OptimisticConcurrencyException será gerado.If an optimistic concurrency violation has occurred, an OptimisticConcurrencyException is thrown. Você pode resolver uma violação de simultaneidade otimista capturando-a, chamando o Refresh método com os StoreWins ClientWins valores ou e, em seguida, chamando o SaveChanges método novamente.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. Para obter mais informações, consulte como: gerenciar a simultaneidade de dados no contexto do objeto.For more information, see How to: Manage Data Concurrency in the Object Context.