微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – EF Core 2.0 TransactionScope错误

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

当我选择查询时,我们的想法是实现“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.Transactionsis committed to be included in the next EF Core release 2.1跟踪.(更新:EF Core 2.1确实是 added System.Transactions support).

在此之前,如果整个要点是使用ReadUncommitted的事务,您可以尝试使用显式EF Core IDbTransactionBeginTransaction(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;
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐