Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinqToSql static DataContext in a web application

In a web application that I have run across, I found the following code to deal with the DataContext when dealing with LinqToSQL

public partial class DbDataContext
  {
    public static DbDataContext DB
    {
      get
      {
        if (HttpContext.Current.Items["DB"] == null)
          HttpContext.Current.Items["DB"] = new DbDataContext();
        return (DbDataContext)HttpContext.Current.Items["DB"];
      }
    }
  }

Then referencing it later doing this:

DbDataContext.DB.Accounts.Single(a => a.accountId == accountId).guid = newGuid;
DbDataContext.DB.SubmitChanges();

I have been looking into best practices when dealing with LinqToSQL.

I am unsure about the approach this one has taken when dealing with DataContext not being ThreadSafe and keeping a static copy of it around.

Is this a good approach to take in a web application?

@Longhorn213 - Based on what you said and the more I have read into HttpContext because of that, I think you are right. But in the application that I have inherited it is confusing this because at the beginning of each method they are requerying the db to get the information, then modifying that instance of the datacontext and submitting changes on it.

From this, I think this method should be discouraged because it is giving the false impression that the datacontext is static and persisting between requests. If a future developer thinks that requerying the data at the beginning of a method because they think it is already there, they could run into problems and not understand why.

So I guess my question is, should this method be discouraged in future development?

like image 333
SBurris Avatar asked Jun 02 '09 17:06

SBurris


1 Answers

This is not a static copy. Note that the property retrieves it from Context.Items, which is per-request. This is a per-request copy of the DataContext, accessed through a static property.

On the other hand, this property is assuming only a single thread per request, which may not be true forever.

like image 184
John Saunders Avatar answered Sep 30 '22 09:09

John Saunders