ObjectTrackingEnabled Does not Work!
Today I was messing around with the datacontext that I created for linq to SQL NorthWind database. One of the ways to improve performance for the datacontext for web scenarios is turn off object tracking on the context. If you are using the context for read only purpose rather than insert update or delete, than you do not need to bear the heavy cost of object tracking service. But what I have found out recently is, if you turn off object tracking on your datacontext, you loose the ability to traverse relationship. For example, if you traversing one one to one relation like Customer.Address.City than you would get a null reference exception. If you navigate a many to many relationship like Customer.Orders.Count(), you will get 0 despite the fact that a particular customer would have orders.
static void Main(string[] args)
{
//tracked
NorthWindDataContext tracked = new NorthWindDataContext();
//object tracking disabled.
NorthWindDataContext nontracked = new NorthWindDataContext();
nontracked.ObjectTrackingEnabled = false;
//context with loading options
NorthWindDataContext loadoption = new NorthWindDataContext();
loadoption.ObjectTrackingEnabled = false;
DataLoadOptions option = new DataLoadOptions();
option.LoadWith<Customer>(c => c.Orders);
loadoption.LoadOptions = option;
//returns 6 orders for the customer.
Customer customer = tracked.Customers.First();
Console.WriteLine("Orders retrieved from tracking context {0}",
customer.Orders.Count());
//you get 0 orders because tracking is disabled.
Customer customer1 = nontracked.Customers.First();
Console.WriteLine("Orders retrieved from non tracking context {0}",
customer1.Orders.Count());
//use the dataload option
Customer customer2 = loadoption.Customers.First();
Console.WriteLine("Orders retrieved using load option on context {0}",
customer2.Orders.Count());
}
Here is the how the screen shot with results look like.
In the above code, I am showing different behaviors of the datacontext and how you can turn off objecttracking and still be able to traverse relationship. The first example prints 6 orders for the customers but the second example, prints 0 orders and that is because object tracking is turned off on the context which somehow messes up the context in being able to retrieve the correct orders from the context. Not sure if this a feature or its a bug, but this is the way it currently works. In order to ensure that you get the right orders even after turning off object tracking you can use DataLoadOptions. DataLoadOptions is like a hint that you are giving to the context telling, hey while you are getting Customers, go ahead and also retrieve Orders for those customers as well. There in the last output, you will notice that you are once again getting the right order despite the ObjectTrackingEnabled is set to false.