Change detection

Most of the time change-tracking works exactly as you’d expect it to, but there are a few wrinkles to the change-tracking mechanism that you should be aware of, just in case you run into a situation in which it doesn’t:

Change-tracking mechanisms

There are two methods of change-tracking used by the Entity Framework: SNAPSHOT TRACKING, which compares the current and original values of properties during SaveChanges() and PROXY TRACKING, which notifies Entity Framework of changes as they occur. The ObjectContext API always uses proxy tracking, which means that changes that you make to an entity are always handled immediately.

When you use the DbContext API, Entity Framework will use snapshot tracking unless your entity classes comply with the rules for proxy-creation. (See “Creating Change Proxies” on the next page for details.) You can disable proxy creation by using the ProxyCreationEnabled property of either ObjectContext.ContextOptions or the DbContext.Configuration. Both are true by default.

DetectChanges()

When the DbContext.DetectChanges() method is called on the context, it will compare the current values of all the entities to a snapshot of the original values it created when the entity was first loaded.

In the DbContext API, the DetectChanges() method is called automatically when you call a method to add or remove an entity from the set, when you retrieve a state entry, when you retrieve validation errors (more on that in the next section) and when you call SaveChanges(). In the ObjectContext API, DetectChanges() is only called by SaveChanges(). In both APIs, you can call DetectChanges() yourself whenever you want to be sure that you’re working with the most up-to-date information.

Performance

There is a difference in performance between the two change-tracking mechanisms, but it’s unlikely to be discernible unless you’re working with thousands or hundreds of thousands of entities. Unfortunately, there aren’t any definite rules for when to use which mechanism because it depends on the kinds of changes that your application is making.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset