首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Linq to SQL进行NOLOCK

使用Linq to SQL进行NOLOCK
EN

Stack Overflow用户
提问于 2009-08-03 05:47:00
回答 5查看 56.8K关注 0票数 73

是否有可能让Linq2Sql在其SQL中发出NOLOCK?如果是这样,又是如何做到的呢?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-08-03 05:51:22

是的,所以这里有一个条目from my blog

NOLOCK提示本质上等同于将查询包装在“隔离级别”设置为“读取未提交”的事务中。这意味着查询并不关心内容是否正在被写入到它正在读取的行中-它将读取“脏”数据并将其作为结果集的一部分返回。

事实证明,您可以使用.NET 2.0中引入的旧System.Transactions名称空间来完成整个“读取未提交”事务。下面是一些示例代码:

using (var txn = new TransactionScope( TransactionScopeOption.Required,new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted } )) { //您的LINQ to SQL查询转到此处}

因此,我创建了一个新的TransactionScope对象,并告诉它使用读未提交的隔离级别。"using“语句中的查询现在的行为就像它的所有表都在使用NOLOCK提示进行读取一样。

以下是谷歌搜索"linq sql nolock“的第一个结果:

InfoQ: Implementing NOLOCK with LINQ to SQL and LINQ to Entities

Matt Hamilton - LINQ to SQL and NOLOCK Hints : Mad Props!

Scott Hanselman's Computer Zen - Getting LINQ to SQL and LINQ to ...

票数 89
EN

Stack Overflow用户

发布于 2014-10-31 13:44:34

进一步了解国王的LinqPad My Extensions addition

代码语言:javascript
复制
public static IQueryable<T> DumpNoLock<T>(this IQueryable<T> query)
{
    using (var txn = GetNewReadUncommittedScope())
    {
        return query.Dump();
    }   
}

public static System.Transactions.TransactionScope GetNewReadUncommittedScope()
{
    return new System.Transactions.TransactionScope(
        System.Transactions.TransactionScopeOption.RequiresNew,
        new System.Transactions.TransactionOptions
        {
            IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
        });
}
public static IQueryable<T> DumpNoLock<T>(this IQueryable<T> query, string description)
{
    using (var txn = GetNewReadUncommittedScope())
    {
        return query.Dump(description);
    }   
}

public static List<T> ToListNoLock<T>(this IQueryable<T> query)
{
    using (var txn = GetNewReadUncommittedScope())
    {
        return query.ToList();
    }   
}

public static U NoLock<T,U>(this IQueryable<T> query, Func<IQueryable<T>,U> expr)
{
    using (var txn = GetNewReadUncommittedScope())
    {
        return expr(query);
    }   
}

最后一个意味着您可以对没有显式编写的NoLock的任何求值查询执行NOLOCK (就像我为上面的ToListNoLock编写的一样)。所以,举个例子:

代码语言:javascript
复制
somequery.NoLock((x)=>x.Count()).Dump();

将使用NOLOCK计算查询。

请注意,您必须确保计算的是查询。例如,与.Distinct().Count().Dump()相比,.NoLock((x)=>x.Distinct()).Count().Dump()不会做任何有用的不同。

票数 24
EN

Stack Overflow用户

发布于 2013-10-04 19:51:59

一种简单的方法可能是在DataContext类上运行命令

代码语言:javascript
复制
using (var dataContext = new DataContext())
{
  dataContext.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");

  // Your SQL query
}
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1220807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档