.net 实体框架核心:使用NOLOCK读取和选择记录

i86rm4rw  于 2023-03-13  发布在  .NET
关注(0)|答案(1)|浏览(207)

如何在实体框架核心中使用NOLOCK读取/选择a?(避免OLTP数据库中的锁定/阻塞/死锁)。这是一个示例选择查询。

var data= _dbContext.Set<ProductOrder>()
            .Where(c => c.ProductTypeId == this.productTypeId && c.saleYear == this.saleYear)
            .ToList();

使用Net Core 3.1和SQL Server 2016数据库。

icnyk63a

icnyk63a1#

您可以将NOLOCKEF Core一起使用,如下所示

using (new TransactionScope(TransactionScopeOption.Required, new TransactionOptions
{
    IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
}))
{
    using (var db = new YourDbContext())
    {
        var data = db.Set<ProductOrder>()
            .Where(c => c.ProductTypeId == this.productTypeId && c.saleYear == this.saleYear)
            .ToList();
    }
}

更好的解决方案:

您可以创建一个扩展方法来创建具有ReadUncommitted状态的TransactionScopeOption

public static async Task<List<T>> ToListWithNoLockAsync<T>(this IQueryable<T> query, CancellationToken cancellationToken = default, Expression<Func<T, bool>> expression = null)
{
    List<T> result = default;
    using (var scope = CreateTrancation())
    {
        if (expression != null)
        {
            query = query.Where(expression);
        }
        result = await query.ToListAsync(cancellationToken);
        scope.Complete();
    }
    return result;
}
private static TransactionScope CreateTrancation()
{
    return new TransactionScope(TransactionScopeOption.Required,
                                new TransactionOptions()
                                {
                                    IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted
                                },
                               TransactionScopeAsyncFlowOption.Enabled);
}

用法:

var categories = dbContext.Categories
                          .AsNoTracking()
                          .Where(a => a.IsDelete == false)
                          .ToListWithNoLockAsync();

注:

如果要为async方法创建具有ReadUnCommited状态的事务,则应在TransactionScope中使用TransactionScopeAsyncFlowOption.Enabled
这个存储库可能对你很有帮助。
更多信息:Implementing NOLOCK in EntityFramework .

相关问题