views:

624

answers:

1

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?

+4  A: 

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;
        }
    }
}
Marc Gravell