Linq to sql 将linq修改为sql commandtext时,是否应关闭连接?

Linq to sql 将linq修改为sql commandtext时,是否应关闭连接?,linq-to-sql,connection,nolock,Linq To Sql,Connection,Nolock,我正在将linq的commandtext修改为sql,以强制它使用nolock,如下所示 if (db.Connection.State == System.Data.ConnectionState.Closed) db.Connection.Open(); var cmd = db.GetCommand(db.Customers.Where(p => p.ID == 1)); cmd.CommandText = cmd.CommandText.Replace("[Custom

我正在将linq的commandtext修改为sql,以强制它使用nolock,如下所示

if (db.Connection.State == System.Data.ConnectionState.Closed)
    db.Connection.Open();

var cmd = db.GetCommand(db.Customers.Where(p => p.ID == 1));

cmd.CommandText = cmd.CommandText.Replace("[Customers] AS [t0]", "[Customers] AS [t0] WITH (NOLOCK)");

var results = db.Translate(cmd.ExecuteReader());
它是一个MVC应用程序,因此datacontext位于基本控制器中,并且可能在本代码之前使用过,更重要的是,在本代码之后使用过。我应该在这个例行程序中关闭连接吗?或者根本没有?或者只有我在这里打开它


更新:

我现在使用更通用的函数(在DataContext类中)修改commandtext,并在此处打开连接时关闭连接。打开的部分移到了ExecuteReader。到目前为止,它一直在工作,并减少了零星的僵局问题。结果不必精确到第二个

    public List<T> GetWithNolock<T>(IQueryable<T> query)
    {
        // to skip nolock, just...
        // return query.ToList();

        List<T> results = null;

        bool opened = false;

        try
        {
            if (Connection.State == System.Data.ConnectionState.Closed)
            {
                Connection.Open();

                opened = true;
            }

            using (var cmd = GetCommand(query))
            {
                cmd.CommandText = Regex.Replace(cmd.CommandText, @"((from|inner join) \[dbo.*as \[t\d+\])", "$1 with (nolock)", RegexOptions.IgnoreCase);

                results = Translate<T>(cmd.ExecuteReader()).ToList();
            }
        }
        finally
        {
            if (opened && Connection.State == System.Data.ConnectionState.Open)
            {
                Connection.Close();
            }
        }

        return results;
    }
public List GetWithNolock(IQueryable查询)
{
//要跳过nolock,只需。。。
//返回query.ToList();
列表结果=空;
bool opened=false;
尝试
{
if(Connection.State==System.Data.ConnectionState.Closed)
{
Connection.Open();
开放=真;
}
使用(var cmd=GetCommand(查询))
{
cmd.CommandText=Regex.Replace(cmd.CommandText,@“((从内部连接)\[dbo.*as\[t\d+\])”,“$1 with(nolock)”,RegexOptions.IgnoreCase);
结果=翻译(cmd.ExecuteReader()).ToList();
}
}
最后
{
if(opened&&Connection.State==System.Data.ConnectionState.Open)
{
Connection.Close();
}
}
返回结果;
}
我过去发现,以推荐的方式使用事务会导致站点一夜之间连接耗尽。据我所知,这是linq to sql中的一个缺陷。可能有办法解决它,但我正试图保持我的主代码简单明了。我现在“只是”必须这样做

var users = GetWithNolock<User>(
  Users
  .Where(u => my query
);
var users=GetWithNolock(
使用者
.Where(u=>我的查询
);

如果打开它,应该将其关闭。其他LinqToSql操作与此模式匹配

在我的代码中,我无条件地打开连接并最终关闭连接。如果有人递给我一个打开的连接,那是他们的错,我碰巧为他们关闭了它

您可以将打开连接延迟到ExecuteReader之前