Object Tracking of EF
The ObjectStateManager is used by the object context to keep track of entities that are loaded into the context.
// Summary: // Occurs when entities are added to or removed from the state manager. public event CollectionChangeEventHandler ObjectStateManagerChanged;
If two different queries are done that return the same record from the database, the state manager is aware of that and does not create a new entity. Instead, the same entity is returned.
private static void TrackingDemo() { using (var data = new Formula1Entities()) { data.ObjectStateManager.ObjectStateManagerChanged += ObjectStateManager_ObjectStateManagerChanged; Racer niki1 = data.Racers.Where("it.Country='Austria' && it.Lastname='Lauda'").First(); Racer niki2 = data.Racers.Where("it.Country='Austria'"). OrderBy("it.Wins DESC").First(); if (Object.ReferenceEquals(niki1, niki2)) { Console.WriteLine("the same object"); } } } static void ObjectStateManager_ObjectStateManagerChanged(object sender, CollectionChangeEventArgs e) { Console.WriteLine("Object State change—action: {0}", e.Action); Racer r = e.Element as Racer; if (r != null) Console.WriteLine("Racer {0}", r.Lastname); }
The event of the ObjectStateManagerChanged of the ObjectStateManager occurs only once, and the references niki1 and niki2 are indeed the same.

浙公网安备 33010602011771号