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

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

问题描述

在我遇到的一个web应用程序中,我在处理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"];
      }
    }
  }

然后在以后引用它:

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 并保留它的静态副本时所采取的方法.

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 的了解越多,我认为您是对的.但是在我继承的应用程序中,这令人困惑,因为在每个方法的开头,他们都重新查询数据库以获取信息,然后修改数据上下文的该实例并提交更改.

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

推荐答案

这不是静态副本.请注意,该属性从 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天全站免登陆