NOLOCK with Linq to SQL

后端 未结 5 605
小鲜肉
小鲜肉 2020-11-30 23:01

Is it possible to get Linq2Sql to emit a NOLOCK in its SQL? And if so, how?

5条回答
  •  渐次进展
    2020-11-30 23:32

    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().

提交回复
热议问题