是否有可能让Linq2Sql在其SQL中发出NOLOCK?如果是这样,又是如何做到的呢?
发布于 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 ...
发布于 2014-10-31 13:44:34
进一步了解国王的LinqPad My Extensions addition
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编写的一样)。所以,举个例子:
somequery.NoLock((x)=>x.Count()).Dump();将使用NOLOCK计算查询。
请注意,您必须确保计算的是查询。例如,与.Distinct().Count().Dump()相比,.NoLock((x)=>x.Distinct()).Count().Dump()不会做任何有用的不同。
发布于 2013-10-04 19:51:59
一种简单的方法可能是在DataContext类上运行命令
using (var dataContext = new DataContext())
{
dataContext.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
// Your SQL query
}https://stackoverflow.com/questions/1220807
复制相似问题