/// <summary> /// 相似SqlServer nolock 查詢擴展 /// Like SqlServer Nolock /// </summary> public static class NoLockQuery { public static List<T> ToListReadUncommitted<T>(this IQueryable<T> query) { using (var scope = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted })) { List<T> toReturn = query.ToList(); scope.Complete(); return toReturn; } } public static int CountReadUncommitted<T>(this IQueryable<T> query) { using (var scope = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted })) { int toReturn = query.Count(); scope.Complete(); return toReturn; } } public static async Task<List<T>> ToListReadUncommittedAsync<T>(this IQueryable<T> query) { using (var scope = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }, TransactionScopeAsyncFlowOption.Enabled )) { List<T> toReturn = await query.ToListAsync(); scope.Complete(); return toReturn; } } public static async Task<int> CountReadUncommittedAsync<T>(this IQueryable<T> query) { using (var scope = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }, TransactionScopeAsyncFlowOption.Enabled )) { int toReturn = await query.CountAsync(); scope.Complete(); return toReturn; } } }
項目中使用EntityFramework,能夠使用下面這段代碼進行nolock查詢:須要添加System.Transactions程序集的引用
若是封裝的話,執行的時候,就須要傳一個代碼片斷進去,委託在這種狀況就派上用場了,咱們能夠使用委託來改進一下,也就是查詢數據庫時候的邏輯代碼代由委託傳遞進去。
public static void NoLockInvokeDB(Action action) { var transactionOptions = new System.Transactions.TransactionOptions(); transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOptions)) { try { action(); } finally { transactionScope.Complete(); } } }
調用:
sql
NoLockInvokeDB(() => { using (var db = new TicketDB()) { lst = db.User.ToList(); } });