问题描述
我试图在EntityFramework Core 2.0的SELECT查询中使用TransactionScope。但是,我收到此错误消息:不支持加入环境事务。
I am trying to use TransactionScope in my SELECT query in EntityFramework Core 2.0. However I am getting this error : "Enlisting in Ambient transactions is not supported."
该想法是实现 NO LOCK选项(我知道在选择查询时适当设置该选项不是一个好主意,但这是供应商的要求。因此,我添加了扩展方法()
The idea is to implement "NO LOCK" option (I know it's not a good idea to have that option in place but it's vendor's requirement) when I do select query. So I added an extension method (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;
}
}
我也已设置为忽略环境交易警告
And also I have set to ignore the Ambient Transaction Warning.
public static void AddEntityFramework(this IServiceCollection services, string connectionString)
{
services.AddDbContextPool<OptomateContext>(options =>
{
options.UseSqlServer(connectionString);
options.ConfigureWarnings(x => x.Ignore(RelationalEventId.AmbientTransactionWarning));
});
}
我在存储库中有以下查询
And I have the query as below in my repository
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。但我不确定为什么会收到此异常。
I understood that .Net Core 2.0 supports TransactionScope. but I am not sure why I am getting this exception.
知道为什么会这样吗?
推荐答案
<$ c EF Core中尚不支持$ c> System.Transactions 。 和)。
System.Transactions
are not supported yet in EF Core. The issue is tracked by #5595: Enable support for System.Transactions and is committed to be included in the next EF Core release 2.1. (Update: EF Core 2.1 indeed added System.Transactions support).
在此之前,如果要点是使用 ReadUncommitted
,则可以尝试使用显式EF Core 通过扩展方法。不幸的是,它不能像您当前的自定义扩展方法中那样完全封装,并且需要传递 DbContext
实例:
Until then, if the whole point is to use transaction with ReadUncommitted
, you can try using the explicit EF Core IDbTransaction
through BeginTransaction(DatabaseFacade, IsolationLevel)
extension method. Unfortunately it cannot be fully encapsulated like in your current custom extension method and requires passing the DbContext
instance:
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;
}
}
这篇关于EF Core 2.0 TransactionScope错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!