简体   繁体   中英

ObjectTrackingEnabled and 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.

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!

In reference to:

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

The query performance enhance comes from NOT tracking. So you want to disable this feature on READ queries, right after the new datacontext is created for this purpose.

ObjectTrackingEnabled = FALSE 

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

For 'traditional' Linq2SQL you need this instead:

 linq2SqlDBContext.ObjectTrackingEnabled = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM