Sunday, January 16, 2011

LINQ to SQL data context modifications

Many times while working with LINQ to SQL I find my self needing some sort of read only version of the data context.  Many operations run against the data context are primarily reading data anyways.  Due to this there is no need for LINQ to SQL to keep track of the state of the items it gets from the database.  Below is an example of the data context modification I use for my personal website.

public partial class DevDaveDataContext
{
    public static DevDaveDataContext ReadOnly
    {
        get
        {
            return new DevDaveDataContext() { ObjectTrackingEnabled = false };
        }
    }

    public static DevDaveDataContext Instance
    {
        get
        {
            return new DevDaveDataContext();
        }
    }

}

With the above code in place, here are a couple different ways I could access the data context.

using (var db = DevDaveDataContext.ReadOnly)
{
    ...
}

var db = DevDaveDataContext.Instance;
var db = DevDaveDataContext.ReadOnly;

No comments:

Post a Comment