diff options
author | vman <public@vaughnnugent.com> | 2022-11-16 14:07:28 -0500 |
---|---|---|
committer | vman <public@vaughnnugent.com> | 2022-11-16 14:07:28 -0500 |
commit | 3fb601d14354c867e1ead94b027c99c4a2fc15b5 (patch) | |
tree | 5bf01312166d97eff255d1fdcd26bf314cebcf76 /VNLib.Plugins.Extensions.Data/TransactionalDbContext.cs | |
parent | c3419e3e43f773ba9ee1e4854e15da873829fbd7 (diff) |
Add project files.
Diffstat (limited to 'VNLib.Plugins.Extensions.Data/TransactionalDbContext.cs')
-rw-r--r-- | VNLib.Plugins.Extensions.Data/TransactionalDbContext.cs | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/VNLib.Plugins.Extensions.Data/TransactionalDbContext.cs b/VNLib.Plugins.Extensions.Data/TransactionalDbContext.cs new file mode 100644 index 0000000..8573c8f --- /dev/null +++ b/VNLib.Plugins.Extensions.Data/TransactionalDbContext.cs @@ -0,0 +1,69 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Storage; + +namespace VNLib.Plugins.Extensions.Data +{ + public abstract class TransactionalDbContext : DbContext, IAsyncDisposable, IDisposable + { + /// <summary> + /// <inheritdoc/> + /// </summary> + protected TransactionalDbContext() + {} + /// <summary> + /// <inheritdoc/> + /// </summary> + protected TransactionalDbContext(DbContextOptions options) : base(options) + {} + + /// <summary> + /// The transaction that was opened on the current context + /// </summary> + public IDbContextTransaction? Transaction { get; set; } + ///<inheritdoc/> + public override void Dispose() + { + //dispose the transaction + this.Transaction?.Dispose(); + base.Dispose(); + } + + /// <summary> + /// Opens a single transaction on the current context. If a transaction is already open, + /// it is disposed and a new transaction is begun. + /// </summary> + public async Task OpenTransactionAsync(CancellationToken cancellationToken = default) + { + //open a new transaction on the current database + this.Transaction = await base.Database.BeginTransactionAsync(cancellationToken); + } + /// <summary> + /// Invokes the <see cref="IDbContextTransaction.Commit"/> on the current context + /// </summary> + public Task CommitTransactionAsync(CancellationToken token = default) + { + return Transaction != null ? Transaction.CommitAsync(token) : Task.CompletedTask; + } + /// <summary> + /// Invokes the <see cref="IDbContextTransaction.Rollback"/> on the current context + /// </summary> + public Task RollbackTransctionAsync(CancellationToken token = default) + { + return Transaction != null ? Transaction.RollbackAsync(token) : Task.CompletedTask; + } + ///<inheritdoc/> + public override async ValueTask DisposeAsync() + { + //If transaction has been created, dispose the transaction + if(this.Transaction != null) + { + await this.Transaction.DisposeAsync(); + } + await base.DisposeAsync(); + GC.SuppressFinalize(this); + } + } +}
\ No newline at end of file |