Is it possible to get Linq2Sql to emit a NOLOCK in its SQL? And if so, how?
Further to theKing's LinqPad My Extensions addition:
public static IQueryable DumpNoLock(this IQueryable 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 DumpNoLock(this IQueryable query, string description)
{
using (var txn = GetNewReadUncommittedScope())
{
return query.Dump(description);
}
}
public static List ToListNoLock(this IQueryable query)
{
using (var txn = GetNewReadUncommittedScope())
{
return query.ToList();
}
}
public static U NoLock(this IQueryable query, Func,U> expr)
{
using (var txn = GetNewReadUncommittedScope())
{
return expr(query);
}
}
The last one means you can do a NOLOCK
on any evaluating queries you haven't a NoLock
explicitly written for (like I've got for ToListNoLock
above). So, for example:
somequery.NoLock((x)=>x.Count()).Dump();
will evaluate the query with NOLOCK
.
Note that you have to ensure you're evaluating the query. E.g. .NoLock((x)=>x.Distinct()).Count().Dump()
won't do anything usefully different from .Distinct().Count().Dump()
.