-
Notifications
You must be signed in to change notification settings - Fork 393
13 efcore pemolo unitofwork
This article introduces transaction management and the Unit of Work pattern in ADNC.
EF Core supports three types of transactions:
SaveChangesDbContextTransactionTransactionScope
By default, EF Core's SaveChangesAsync wraps operations in a transaction as needed. However, there are exceptions in ADNC:
-
Bulk Operations:
ExecuteUpdateAsyncandExecuteDeleteAsyncbypass the change tracker and are not controlled bySaveChanges. -
CAP Transactions: CAP operations are outside the standard
SaveChangesscope. -
Raw SQL: Native SQL execution is not managed by
SaveChanges.
ADNC uses DbContextTransaction to unify transaction control. If your business logic involves multiple write operations (≥ 2), it is recommended to explicitly enable transaction control.
The easiest way to use transactions is via the [UnitOfWork] attribute on service interfaces in the Application.Contracts layer.
// Local Transaction
[UnitOfWork]
Task<AppSrvResult> UpdateAsync(long id, DeptUpdationDto input);
// Distributed Transaction (CAP)
[UnitOfWork(Distributed = true)]
Task<AppSrvResult> ProcessPayingAsync(long transactionLogId, long customerId, decimal amount);The framework automatically manages the transaction lifecycle (Begin, Commit, Rollback) through an interceptor.
If you prefer manual control or have complex requirements, you can inject IUnitOfWork into your service:
public class xxxAppService
{
private readonly IUnitOfWork _uow;
public xxxAppService(IUnitOfWork uow) => _uow = uow;
public async Task DemoMethod()
{
try
{
await _uow.BeginTransactionAsync(distributed: false);
// Operation 1
// Operation 2
await _uow.CommitAsync();
}
catch (Exception)
{
await _uow.RollbackAsync();
throw;
}
}
}If this helps, please Star & Fork.
- Official Website: https://aspdotnetcore.net
- Online Demo: https://online.aspdotnetcore.net
- Documentation: https://docs.aspdotnetcore.net
- Code Generator: https://code.aspdotnetcore.net