63 lines
1.7 KiB
C#
63 lines
1.7 KiB
C#
using System;
|
|
using System.Data;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Storage;
|
|
|
|
namespace IRaCIS.Core.Infra.EFCore
|
|
{
|
|
public class EFUnitOfWork<TDbContext> :
|
|
IEFUnitOfWork<TDbContext> where TDbContext : DbContext
|
|
, IDisposable
|
|
{
|
|
public DbContext DbContext { get; }
|
|
// https://docs.microsoft.com/en-us/ef/core/saving/transactions
|
|
private IDbContextTransaction _transaction;
|
|
|
|
public EFUnitOfWork(TDbContext dbContext)
|
|
{
|
|
DbContext = dbContext;
|
|
}
|
|
|
|
|
|
public void BeginTransaction(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
|
|
{
|
|
if (DbContext.Database.IsRelational())
|
|
{
|
|
_transaction = DbContext.Database.BeginTransaction(isolationLevel);
|
|
}
|
|
}
|
|
|
|
public async Task BeginTransactionAsync(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
|
|
{
|
|
if (DbContext.Database.IsRelational())
|
|
{
|
|
_transaction = await DbContext.Database.BeginTransactionAsync(isolationLevel);
|
|
}
|
|
}
|
|
|
|
//失败 自动回退
|
|
public virtual void Commit()
|
|
{
|
|
DbContext.SaveChanges();
|
|
_transaction?.Commit();
|
|
}
|
|
|
|
public virtual async Task CommitAsync(CancellationToken cancellationToken)
|
|
{
|
|
await DbContext.SaveChangesAsync(cancellationToken);
|
|
|
|
await _transaction?.CommitAsync(cancellationToken);
|
|
|
|
}
|
|
|
|
public virtual void Dispose()
|
|
{
|
|
_transaction?.Dispose();
|
|
}
|
|
|
|
|
|
}
|
|
}
|