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

使用Linq to SQL进行NOLOCK
EN

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

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

EN

回答 4

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用户

发布于 2012-08-09 05:45:44

下面是与LINQPAD一起使用的扩展方法

代码语言:javascript
复制
    public static IQueryable<T> Dump2<T>(this IQueryable<T> query)
{
    using (var txn = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew, 
        new TransactionOptions
        {       
            IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
        }))
    {
        return query.Dump();
    }   
}

然后你可以这样调用它:

代码语言:javascript
复制
MyTable.Where(t => t.Title = "Blah").Dump2();
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1220807

复制
相关文章

相似问题

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