Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectTrackingEnabled and linq-to-sql

Tags:

c#

linq-to-sql

I read here that when querying data for a read operation, setting ObjectTrackingEnabled to false 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 ObjectTrackingEnabled to true in a query, do I need to set it to false before returning or am I just setting ObjectTrackingEnabled for the particular instance of the data context and the following time I'll instantiate a new data context the value of ObjectTrackingEnabled will revert back to its default state of false?

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

Thanks.

like image 451
frenchie Avatar asked Oct 22 '12 22:10

frenchie


2 Answers

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!

like image 97
Dimitar Velitchkov Avatar answered Oct 05 '22 03:10

Dimitar Velitchkov


Your tags and subject line say 'Linq2SQL' but your question is about Entity Framwork.

For 'traditional' Linq2SQL you need this instead:

 linq2SqlDBContext.ObjectTrackingEnabled = false;
like image 31
Simon_Weaver Avatar answered Oct 05 '22 04:10

Simon_Weaver