在Web应用程序LinqToSql静态的DataContext [英] LinqToSql static DataContext in a web application

查看:116
本文介绍了在Web应用程序LinqToSql静态的DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我已经运行在整个Web应用程序,我发现下面的code。与LinqToSQL打交道时要处理的DataContext的

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();

我与LinqToSQL打交道时一直在寻找到最佳做法。

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

我不确定与DataContext的不是ThreadSafe的和周围保持它的静态副本时,这一个人采取的方法。

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.

这是一个好方法采取在Web应用程序?

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

@ Longhorn213 - 根据你说什么,我就越已经读入正因为如此HttpContext的,我想你是对的。但是在我继承了这是混淆了这一点,因为在每一个方法的开头他们再次查询数据库来获取信息,然后修改的datacontext的该实例并在其上提交的变化。应用

@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.

在此,我觉得这个方法应该,因为这是给假IM pression了的datacontext是静态和请求之间持续气馁。如果将来开发商认为,在方法的开头再次查询数据,因为他们认为这是已经在那里,他们可能会遇到的问题,不明白为什么。

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?

推荐答案

这是不是一个静态的副本。需要注意的是财产Context.Items,这是每个请求进行检索。这是在DataContext的每个请求的副本,通过静态属性访问。

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.

这篇关于在Web应用程序LinqToSql静态的DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆