A Linq to SQL DataContext by default tracks all changes to Entities/Objects that are retrieved through it. In order to track the changes, the DataContext subscribes to the Events exposed by INotifyPropertyChanging Interface and INotifyPropertyChanged Interface of each Entity.
Often the result of a query is not intended for modification. For example, when a search query returns potentially hundreds or thousands of items to be displayed in a paged list, subscribing to Events of each item is unnecessary and will affect performance.
The solution to this is turning Object Tracking off on the DataContext, before executing the read only queries. It is accomplished by setting ObjectTrackingEnabled = false. Here is an example:
//Assuming the name of our custom DataContext is dbContext
dbContext context = new dbContext();
context.ObjectTrackingEnabled = false;
//Now query the database as usual
var q = context.Customers.Where(c => c.Name.StartsWith("John"));
Since it is very common to perform Read Only Queries like this. I prefer to have a static Property on the DataContext that returns a Read Only instance. This way setting ObjectTrackingEnabled every time can be avoided. Here is the ReadOnly static property:
/* Author: Abu Haider
/* January 2010
/* www.haiders.net
/* Adds a static method on a DataContext to return a ReadOnly instance */
public partial class dbContext //Your DataContext Class
{
public static dbContext ReadOnly
{
get { return new dbContext() { ObjectTrackingEnabled = false }; }
}
}
/* That's it */
Now the Read only instance can be queried as follows:
var q = dbContext.ReadOnly.Customers.Where( c => c.Name.StartsWith("John"));
No more having to create new instances of the DataContext and explicitly setting the ObjectTrackingEnabled. Besides, I think it also makes the code more readable by clearly indicating that the result set is intended for Read Only operations.
Posted on January 4, 2010 11:01 by
Haider