Wednesday, March 23, 2011

Entity Framework 4: Disable change tracking

The Entity Framework ObjectContext implements the unit of work pattern and does all the change tracking for you. However sometimes you just need to get some readonly data(for example in a CQRS architecture). In that case change tracking is just an extra performance penalty. 

How to Disable the Change Tracking Option

In Entity Framework, change tracking is being done by the ObjectStateManager. The ObjectStateManager maintains object state and identity management for entity type instances and relationship instances. In order to disable change tracking you use the MergeOption.NoTracking option of the MergeOption enumeration. Using that option will retrieve entities in a detached state.

There are 2 places where you can specify this option:

One place to disable the change tracking is when we retrieve data with the ObjectQuery object. One of the overloaded constructors of the ObjectQuery
gets as a parameter the MergeOption enumeration.

var query = new ObjectQuery<Employee>("SELECT VALUE e FROM NorthwindEntities.Employee AS e",context,MergeOption.NoTracking);

Another place to disable the change tracking is on the EntitySet level.

context.Employee.MergeOption = MergeOption.NoTracking;

I still like the more explicit approach of the NHibernate Stateless Session more. But that’s just me…

No comments: