1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- using System;
- using System.Collections.Generic;
- using System.Data;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace Luticate2.Utils.DataAccess
- {
- public class LuEfTransactionScope
- {
- protected IDictionary<Type, DbContext> Contexts;
-
- private readonly IServiceProvider _serviceProvider;
-
- public LuEfTransactionScope(IServiceProvider serviceProvider)
- {
- _serviceProvider = serviceProvider;
- Contexts = new Dictionary<Type, DbContext>();
- }
-
- public TDbContext GetTransactedDbContext<TDbContext>()
- where TDbContext : DbContext
- {
- if (Contexts.ContainsKey(typeof(TDbContext)))
- {
- return (TDbContext) Contexts[typeof(TDbContext)];
- }
- return null;
- }
-
- public bool BeginTransaction<TDbContext>(TDbContext dbContext, IsolationLevel? level = null)
- where TDbContext : DbContext
- {
- if (dbContext == null)
- {
- dbContext = GetTransactedDbContext<TDbContext>();
- if (dbContext == null)
- {
- dbContext = _serviceProvider.GetService<TDbContext>();
- }
- }
- if (!Contexts.Contains(new KeyValuePair<Type, DbContext>(typeof(TDbContext), dbContext)))
- {
- Contexts.Add(typeof(TDbContext), dbContext);
- }
-
- if (dbContext.Database.CurrentTransaction != null)
- {
- return false;
- }
-
- if (level == null)
- {
- dbContext.Database.BeginTransaction();
- }
- else
- {
- dbContext.Database.BeginTransaction(level.Value);
- }
- return true;
- }
-
- public void CommitTransaction<TDbContext>()
- where TDbContext : DbContext
- {
- try
- {
- GetTransactedDbContext<TDbContext>().Database.CommitTransaction();
- }
- finally
- {
- Contexts.Remove(typeof(TDbContext));
- }
- }
-
- public void RollbackTransaction<TDbContext>()
- where TDbContext : DbContext
- {
- try
- {
- GetTransactedDbContext<TDbContext>().Database.RollbackTransaction();
- }
- finally
- {
- Contexts.Remove(typeof(TDbContext));
- }
- }
- }
- }
|