是否有可能让Linq2Sql在其SQL中发出NOLOCK?如果是这样,又是如何做到的呢?
发布于 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
}
发布于 2012-08-09 05:45:44
下面是与LINQPAD一起使用的扩展方法
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();
}
}
然后你可以这样调用它:
MyTable.Where(t => t.Title = "Blah").Dump2();
https://stackoverflow.com/questions/1220807
复制相似问题