ObjectContext.Refresh Método
Definição
Atualiza objetos específicos no contexto de objeto com os dados da fonte de dados.Updates specific objects in the object context with data from the data source.
Sobrecargas
| Refresh(RefreshMode, IEnumerable) |
Atualiza uma coleção de objetos no contexto de objeto com os dados da fonte de dados.Updates a collection of objects in the object context with data from the data source. |
| Refresh(RefreshMode, Object) |
Atualiza um objeto no contexto de objeto com os dados da fonte de dados.Updates an object in the object context with data from the data source. |
Comentários
A ordem na qual os objetos são atualizados é não determinística.The order in which objects are refreshed is nondeterministic.
Refresh(RefreshMode, IEnumerable)
Atualiza uma coleção de objetos no contexto de objeto com os dados da fonte de dados.Updates a collection of objects in the object context with data from the data source.
public:
void Refresh(System::Data::Objects::RefreshMode refreshMode, System::Collections::IEnumerable ^ collection);
public void Refresh (System.Data.Objects.RefreshMode refreshMode, System.Collections.IEnumerable collection);
member this.Refresh : System.Data.Objects.RefreshMode * System.Collections.IEnumerable -> unit
Public Sub Refresh (refreshMode As RefreshMode, collection As IEnumerable)
Parâmetros
- refreshMode
- RefreshMode
Um valor RefreshMode que indica se as alterações de propriedade no contexto de objeto são substituídas por valores de propriedade da fonte de dados.A RefreshMode value that indicates whether property changes in the object context are overwritten with property values from the data source.
- collection
- IEnumerable
Uma coleção de objetos IEnumerable a serem atualizados.An IEnumerable collection of objects to refresh.
Exceções
collection é null.collection is null.
refreshMode não é válido.refreshMode is not valid.
collection está vazio.collection is empty.
- ou --or-
Um objeto não está anexado ao contexto.An object is not attached to the context.
Comentários
Esse método tem a finalidade dupla de permitir que objetos no contexto de objeto sejam atualizados com dados da fonte de dados e sejam o mecanismo pelo qual os conflitos podem ser resolvidos.This method has the dual purpose of allowing objects in the object context to be refreshed with data from the data source, and being the mechanism by which conflicts can be resolved. Para obter mais informações, consulte salvando alterações e gerenciando a simultaneidade.For more information, see Saving Changes and Managing Concurrency.
A ordem na qual os objetos são atualizados é não determinística.The order in which objects are refreshed is nondeterministic.
Depois que Refresh for chamado, os valores originais do objeto sempre serão atualizados com o valor da fonte de dados, mas os valores atuais poderão ou não ser atualizados com o valor da fonte de dados.After Refresh is called, the object's original values will always be updated with the data source value, but the current values might or might not be updated with the data source value. Isso depende do RefreshMode valor.This depends on the RefreshMode value. O StoreWins modo significa que os objetos na coleção devem ser atualizados para corresponder aos valores da fonte de dados.The StoreWins mode means that the objects in the collection should be updated to match the data source values. ClientWins significa que somente as alterações no contexto do objeto serão persistidas, mesmo se houver outras alterações na fonte de dados.ClientWins means that only the changes in the object context will be persisted, even if there have been other changes in the data source.
Para garantir que os objetos tenham sido atualizados pela lógica do lado da fonte de dados, você pode chamar Refresh com StoreWins depois de chamar o SaveChanges método.To ensure that objects have been updated by data source-side logic, you can call Refresh with StoreWins after you call the SaveChanges method.
Aplica-se a
Refresh(RefreshMode, Object)
Atualiza um objeto no contexto de objeto com os dados da fonte de dados.Updates an object in the object context with data from the data source.
public:
void Refresh(System::Data::Objects::RefreshMode refreshMode, System::Object ^ entity);
public void Refresh (System.Data.Objects.RefreshMode refreshMode, object entity);
member this.Refresh : System.Data.Objects.RefreshMode * obj -> unit
Public Sub Refresh (refreshMode As RefreshMode, entity As Object)
Parâmetros
- refreshMode
- RefreshMode
Um dos valores RefreshMode que especifica qual modo deve ser usado para atualizar o ObjectStateManager.One of the RefreshMode values that specifies which mode to use for refreshing the ObjectStateManager.
- entity
- Object
O objeto a ser atualizado.The object to be refreshed.
Exceções
collection é null.collection is null.
refreshMode não é válido.refreshMode is not valid.
collection está vazio.collection is empty.
- ou --or-
Um objeto não está anexado ao contexto.An object is not attached to the context.
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. O exemplo tenta salvar as alterações, e isso pode causar um conflito de simultaneidade.The example tries to save changes, and this may cause a concurrency conflict. Em seguida, ele mostra como resolver o conflito de simultaneidade atualizando o contexto do objeto antes de salvar as alterações novamente.Then it shows 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
Refresh tem a finalidade dupla de permitir que um objeto seja atualizado com dados da fonte de dados e seja o mecanismo pelo qual os conflitos podem ser resolvidos.Refresh has the dual purpose of allowing an object to be refreshed with data from the data source and being the mechanism by which conflicts can be resolved. Para obter mais informações, consulte salvando alterações e gerenciando a simultaneidade.For more information, see Saving Changes and Managing Concurrency.
A ordem na qual os objetos são atualizados é não determinística.The order in which objects are refreshed is nondeterministic.
Depois que o Refresh método é chamado, os valores originais do objeto sempre serão atualizados com o valor da fonte de dados, mas os valores atuais podem ou não ser atualizados com o valor da fonte de dados.After the Refresh method is called, the object's original values will always be updated with the data source value, but the current values might or might not be updated with the data source value. Isso depende do RefreshMode .This depends on the RefreshMode. O StoreWins modo significa que o objeto deve ser atualizado para corresponder aos valores da fonte de dados.The StoreWins mode means that the object should be updated to match the data source values. O ClientWins valor significa que somente as alterações no contexto do objeto serão persistidas, mesmo se houver outras alterações na fonte de dados.The ClientWins value means that only the changes in the object context will be persisted, even if there have been other changes in the data source.
Para garantir que um objeto tenha sido atualizado pela lógica do lado da fonte de dados, você pode chamar o Refresh método com o StoreWins valor depois de chamar o SaveChanges método.To ensure that an object has been updated by data source-side logic, you can call the Refresh method with the StoreWins value after you call the SaveChanges method.