EF Core 2.0 TransactionScope错误

Ala*_*n B 4 c# entity-framework transactionscope entity-framework-core ef-core-2.0

我试图在EntityFramework Core 2.0的SELECT查询中使用TransactionScope.但是我收到此错误:"不支持在Ambient事务中登记."

当我选择查询时,我们的想法是实现"NO LOCK"选项(我知道这个选项不是一个好主意,但它是供应商的要求).所以我添加了一个扩展方法(带有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;
    }
}
Run Code Online (Sandbox Code Playgroud)

而且我也设置忽略环境交易警告.

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

我在我的存储库中有如下查询

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();
}
Run Code Online (Sandbox Code Playgroud)

我明白.Net Core 2.0支持TransactionScope.但我不确定为什么我会得到这个例外.

知道为什么会这样吗?

Iva*_*oev 7

System.Transactions在EF Core中尚不支持.该问题由#5595跟踪:启用对System.Transactions的支持,承诺包含在下一个EF Core版本2.1中.(更新: EF Core 2.1确实添加了System.Transactions支持).

在此之前,如果整点都是使用事务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;
    }
}
Run Code Online (Sandbox Code Playgroud)