c# – EF Core 2.0 TransactionScope错误
发布时间:2020-12-15 23:41:00 所属栏目:百科 来源:网络整理
导读:我试图在EntityFramework Core 2.0的SELECT查询中使用TransactionScope.但是我收到此错误:“不支持在Ambient事务中登记.” 当我选择查询时,我们的想法是实现“NO LOCK”选项(我知道这个选项不是一个好主意,但它是供应商的要求).所以我添加了扩展方法(Entity
我试图在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.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 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; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |