(da MSDN) ObjectStateManager tracks query results, and provides logic to merge multiple overlapping query results. It also performs in-memory change tracking when a user inserts, deletes, or modifies objects, and provides the change set for updates. This change set is used by the change processor to persist modifications.
La classe ObjectStateManager in generale gestisce lo stato dei nostri EntityObject. In quei casi in cui i nostri dati devono essere semplicemente presentati in modalità read only può essere utile disabilitare il change tracking dell’ ObjectContext, ottenendo un incremento di performance talvolta significativo.
In particolare, per disabilitare il change tracking occorre utilizzare l’opzione MergeOption.NoTracking dell’enumeration MergeOption, che permette di lavorare con Entità aventi EntityState ‘Detached’. Fondamentalmente esistono due modi per disabilitare il change tracking:
- Utilizzando l’oggetto ObjectQuery. Esiste infatti un overload del costruttore che permette di specificare l’opzione MergeOption desiderata.
- A livello di EntitySet
Vediamo entrambi gli esempi:
Caso 1
using (NorthwindObjectContext context = new NorthwindObjectContext())
{
ObjectQuery<Customer> queryCustomers = new ObjectQuery<Customer>("SELECT VALUE c FROM NorthwindObjectContext.Customers AS c", context, MergeOption.NoTracking);
foreach (Customer customer in queryCustomers)
{
Console.WriteLine("{0} - {1}", customer.ContactName, customer.EntityState.ToString());
}
}
Caso 2
using (NorthwindObjectContext context = new NorthwindObjectContext())
{
context.Customers.MergeOption = MergeOption.NoTracking;
foreach (Customer customer in context.Customers)
{
Console.WriteLine("{0} - {1}", customer.ContactName, customer.EntityState.ToString());
}
}
Technorati Tag:
Entity Framework