Entity Framework with NOLOCK

Ef 使用类似sqlserver 的nolock 查询扩展类

    /// <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;
            }
        }
    }

参考:http://stackoverflow.com/questions/926656/entity-framework-with-nolock

posted @ 2017-03-22 09:12  碎碎虎  阅读(1613)  评论(0编辑  收藏  举报