Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Is ObjectTrackingEnabled = false worth it for small operations?

Given the following piece of code:

using(var data = new SomeDataContext(ConnectionString))
{
  data.ObjectTrackingEnabled = false;

  foreach(Something in data.Somethings)
     someList.Add(something.SomeProperty);
}

Is it worth it setting object tracking to false? I know it is just one line of code, but it kind of bugs me having to write it all the time. But I have heard that you can have some performance gain by turning it of when you don't need it. And since I just need to quickly read out some data, I don't need the tracking. But is it worth it in such a small piece of code? What is your opinion? Should I use it? Should I not? Why?

like image 332
Svish Avatar asked Feb 10 '09 13:02

Svish


1 Answers

If the context is going to be disposed immediately, it probably isn't worth it - but here's a few thoughts:

  • perhaps write a "fluent" extension method for data-contexts (below)
  • make it the default, by adding a partial OnCreated method that does it

Fluent extension example:

public static class DataContextExt {
    public static T NoTracking<T>(this T ctx)
        where T : DataContext
    {
        ctx.ObjectTrackingEnabled = false;
        return ctx;
    }   

}

Then you can use:

using(var data = new SomeDataContext(ConnectionString).NoTracking())
{...}

Partial method example:

namespace MyData {
    partial class MyDataContext {
        partial void OnCreated() {
            this.ObjectTrackingEnabled = false;
        }
    }
}
like image 69
Marc Gravell Avatar answered Sep 28 '22 07:09

Marc Gravell