You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.2 KiB
71 lines
1.2 KiB
using SqlSugar;
|
|
|
|
namespace Infrastructure.Repository;
|
|
|
|
public interface IUnitOfWork
|
|
{
|
|
SqlSugarScope DbClient { get; }
|
|
|
|
void BeginTransaction();
|
|
|
|
void CommitTransaction();
|
|
|
|
void RollbackTransaction();
|
|
}
|
|
|
|
public class UnitOfWork : IUnitOfWork
|
|
{
|
|
private int _count;
|
|
|
|
private readonly SqlSugarScope? _dbClient;
|
|
|
|
public SqlSugarScope DbClient => _dbClient!;
|
|
|
|
public UnitOfWork(ISqlSugarClient sqlSugarClient)
|
|
{
|
|
if (sqlSugarClient is SqlSugarScope scope)
|
|
{
|
|
_dbClient = scope;
|
|
}
|
|
}
|
|
|
|
public void BeginTransaction()
|
|
{
|
|
lock (this)
|
|
{
|
|
_count++;
|
|
_dbClient?.BeginTran();
|
|
}
|
|
}
|
|
|
|
public void CommitTransaction()
|
|
{
|
|
lock (this)
|
|
{
|
|
_count--;
|
|
if (_count != 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
_dbClient?.CommitTran();
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine(e);
|
|
_dbClient?.RollbackTran();
|
|
}
|
|
}
|
|
}
|
|
|
|
public void RollbackTransaction()
|
|
{
|
|
lock (this)
|
|
{
|
|
_count--;
|
|
_dbClient?.RollbackTran();
|
|
}
|
|
}
|
|
} |