Class DbContextUnitOfWork<TDbContext>
- Namespace
- KYS.EFCore.Library
- Assembly
- KYS.EFCore.Library.dll
IUnitOfWork implementation that wraps a database transaction of a DbContext.
public class DbContextUnitOfWork<TDbContext> : IUnitOfWork, IDisposable, IAsyncDisposable where TDbContext : DbContext
Type Parameters
TDbContextThe type of DbContext whose transaction is managed.
- Inheritance
-
DbContextUnitOfWork<TDbContext>
- Implements
- Inherited Members
Remarks
Disposing the unit of work rolls back any transaction that has not been committed.
The TDbContext instance itself is not disposed, as its lifetime is owned by the caller (e.g. the DI container).
Constructors
DbContextUnitOfWork(TDbContext)
Initializes a new instance of the DbContextUnitOfWork<TDbContext> class.
public DbContextUnitOfWork(TDbContext context)
Parameters
contextTDbContextThe DbContext used to start and commit transactions.
Methods
BeginAsync()
Starts a new database transaction.
public Task BeginAsync()
Returns
- Task
A task that represents the asynchronous operation.
CommitAsync()
Saves all pending changes with SaveChangesAsync(CancellationToken) and commits the current transaction.
public Task CommitAsync()
Returns
- Task
A task that represents the asynchronous operation.
Remarks
This method calls the plain SaveChangesAsync, so no audit records are written. To audit the changes of an
ApplicationDbContext, call SaveChangesWithAuditAsync(Guid?, Formatting?)
before committing.
Exceptions
- InvalidOperationException
BeginAsync() has not been called.
Dispose()
Rolls back any uncommitted transaction and releases it.
public void Dispose()
Dispose(bool)
Releases the resources used by the unit of work.
protected virtual void Dispose(bool disposing)
Parameters
disposingbooltrue to release managed resources (the current transaction); false when called from a finalizer.
DisposeAsync()
Asynchronously rolls back any uncommitted transaction and releases it.
public ValueTask DisposeAsync()
Returns
- ValueTask
A task that represents the asynchronous dispose operation.
RollbackAsync()
Rolls back and disposes the current transaction.
public Task RollbackAsync()
Returns
- Task
A task that represents the asynchronous operation.
Exceptions
- InvalidOperationException
BeginAsync() has not been called.