我正在尝试在 EntityFramework Core 2.0 的 SELECT 查询中使用 TransactionScope。但是我收到此错误:“不支持在环境事务中登记。”
这个想法是在我选择查询时实现“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;
}
}
而且我已经设置忽略环境事务警告。
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。但我不确定为什么会收到此异常。
知道为什么会这样吗?