我正在尝试在EntityFramework Core 2.0中的SELECT查询中使用TransactionScope。然而,我遇到了这个错误:"Enlisting in Ambient transactions is not supported."
我的想法是在执行SELECT查询时实现"NO LOCK"选项(我知道在这种情况下使用该选项不是一个好主意,但这是供应商的要求)。因此,我添加了一个扩展方法(Entity Framework with NOLOCK)。
我知道 .Net Core 2.0 支持 TransactionScope ,但不确定为什么会出现此异常。您有任何想法吗?
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 ,但不确定为什么会出现此异常。您有任何想法吗?