c# - EF Core 2.0 TransactionScope 错误

标签 c# entity-framework entity-framework-core transactionscope ef-core-2.0

我正在尝试在 EntityFramework Core 2.0 的 SELECT 查询中使用 TransactionScope。但是我收到此错误:“不支持在环境事务中登记。”

我的想法是在选择查询时实现“NO LOCK”选项(我知道设置该选项不是一个好主意,但这是供应商的要求)。所以我添加了一个扩展方法(Entity Framework with NOLOCK)

public static async Task<List<T>> ToListReadUncommittedAsync<T>(this IQueryable<T> query)
{
    using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
        new TransactionOptions()
        {
            IsolationLevel = IsolationLevel.ReadUncommitted
        }, TransactionScopeAsyncFlowOption.Enabled))
    {
        var result = await query.ToListAsync();
        scope.Complete();
        return result;
    }
}

而且我还设置了忽略环境事务警告。

public static void AddEntityFramework(this IServiceCollection services, string connectionString)
{
    services.AddDbContextPool<OptomateContext>(options =>
    {
        options.UseSqlServer(connectionString);
        options.ConfigureWarnings(x => x.Ignore(RelationalEventId.AmbientTransactionWarning));
    });
}

我的存储库中有如下查询

public async Task<Patient> GetPatient(Common.Resources.Patient patient)
{
    var pat = await Dbset.Where(x => string.Equals(x.Surname,patient.Surname, 
    StringComparison.CurrentCultureIgnoreCase)).ToListReadUncommittedAsync();                                    

    return pat.FirstOrDefault();
}

我了解到 .Net Core 2.0 支持 TransactionScope。但我不确定为什么会出现此异常。

知道为什么会这样吗?

最佳答案

EF Core 尚不支持

System.Transactions。该问题由 #5595: Enable support for System.Transactions 跟踪和 is committed to be included in the next EF Core release 2.1 . (更新: EF Core 2.1 确实是 added System.Transactions support)。

到那时,如果重点是使用带有 ReadUncommitted 的事务,您可以尝试使用显式 EF Core IDbTransaction通过BeginTransaction(DatabaseFacade, IsolationLevel)扩展方法。不幸的是,它不能像您当前的自定义扩展方法那样完全封装,并且需要传递 DbContext 实例:

public static async Task<List<T>> ToListReadUncommittedAsync<T>(this IQueryable<T> query, DbContext context)
{
    using (var transaction = await context.Database.BeginTransactionAsync(System.Data.IsolationLevel.ReadUncommitted))           {
    {
        var result = await query.ToListAsync();
        transaction.Commit();
        return result;
    }
}

关于c# - EF Core 2.0 TransactionScope 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46577551/

相关文章:

c# - 如何实现asp :DataList in . NET 2.0的分页?

c# - Entity Framework 包括性能不佳

c# - 什么会导致 DbSet 中的持久化实体分离?

c# - 在集合类型上使用大括号初始化程序是否设置了初始容量?

c# - 我可以覆盖 Entity Framework 查询生成器吗?

wpf - 将实体绑定(bind)到 WPF 表单 MVVM

c# - 使用 LINQ 进行实体计数

c# - 将 Guid 传递给存储过程会引发 Microsoft.Data.SqlClient.SqlException : 'Incorrect syntax near ' @Id'. '

c# - 使用 EF Core 防止同步 API 使用

c# - xmlnodelist 到 C# 中的对象列表