frenchie frenchie - 29 days ago 6x
C# Question

ObjectTrackingEnabled and linq-to-sql

I read here that when querying data for a read operation, setting

gives somewhat of a performance boost. My queries look like this:

public return type TheQueryName (some parameters)
using (TheDC MyDC = new TheDC())
var TheQuery = (...).ToList();

return TheQuery;

1) If I want to add the performance enhancement, do I just add the line
ObjectTrackingEnabled = true;
just before the line
var TheQuery = (...).ToList();

2) Also, if I set
in a query, do I need to set it to false before returning or am I just setting
for the particular instance of the data context and the following time I'll instantiate a new data context the value of
will revert back to its default state of

Note: I only plan do add
ObjectTrackingEnabled = false;
to read operations.



ObjectTrackingEnabled controls whether your Data Context (TheDC in your case) will track changes to the entities after they're loaded. Whether you want that or not depends on your specific case.

Naturally, having the Data context do fewer things will make it go faster, but at the expense of burdening you with tracking changes. Why is change tracking cool? Because you can:

  1. Load up some entities from some context
  2. Modify them
  3. Add new ones, delete others
  4. Call SaveChanges and let the data context figure out to do UPDATE queries for modified entities, DELETE for deleted ones, etc

With change tracking disabled, you have to tell the context explicitly what changed, what the new values are, etc.

Assuming you still don't want object tracking, the property is set on each specific data context instance. This means you have to either:

  1. Set it manually for every data context you create
  2. Set it as a default for the context in the context's constructor like so: this.Configuration.AutoDetectChangesEnabled = true; See this blog post for details

Hope this helps!