A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
Microsoft.EntityFrameworkCore
Sahar Ash
0
Reputation points
Hello, I am using Microsoft.EntityFrameworkCore And SQLServer2022, but I have a problem. I added DBContext to my service as scoped, but I get this error.
"The connection is already in a transaction and cannot participate in another transaction."
But if I add it as Transient, I have no problem, please guide me This is also my code
public abstract class BaseOperator<TOut>: IBaseOperation<TOut>
{
protected readonly TOut? Out;
protected IExceptionHandler ExceptionHandler;
protected IUserInfo UserInfo;
static SemaphoreSlim SemaphoreSlim = new SemaphoreSlim(1, 1);
public BaseOperator()
{
ExceptionHandler = ServiceLocator.GetService<IExceptionHandler>();
UserInfo = ServiceLocator.GetService<IUserInfo>();
}
public async Task<TOut> OperateAsync(IDbContextTransaction? DBTransaction = null, DbContext? AlinDBContext = null)
{
if (DBTransaction != null) return await OperateAsync(AlinDBContext, DBTransaction);
await SemaphoreSlim.WaitAsync(2000);
var Context = ServiceLocator.GetService<AlinDBContext>();
using (var Transaction =await Context.Database.BeginTransactionAsync(isolationLevel: IsolationLevel.Serializable))
{
try
{
var Result = await OperateAsync(Context, Transaction);
await Context.Database.CommitTransactionAsync();
return Result;
}
catch (Exception e)
{
await Context.Database.RollbackTransactionAsync();
throw new Exception(e.Message);
}
finally
{
await Transaction.DisposeAsync();
SemaphoreSlim.Release();
}
}
}
protected abstract Task<TOut> OperateAsync(DbContext AlinDBContext, IDbContextTransaction Transaction);
}
public class ServiceLocator
{
public static IServiceProvider ServiceProvider;
public static TService GetService<TService>() => ServiceProvider.GetService<TService>();
}
And In Program.cs :
var ServiceProvider = Services.BuildServiceProvider();
ServiceLocator.ServiceProvider = ServiceProvider;
Developer technologies | .NET | Entity Framework Core
Developer technologies | .NET | Entity Framework Core
Sign in to answer