Skip to content

Commit e408c7f

Browse files
committed
- 增加 CreateUnitOfWork 从外部事务创建;
1 parent 70e5b94 commit e408c7f

2 files changed

Lines changed: 78 additions & 0 deletions

File tree

FreeSql.DbContext/Repository/Extensions/FreeSqlRepositoryExtensions.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using FreeSql;
22
using System;
3+
using System.Data.Common;
34
using System.Linq;
45
using System.Linq.Expressions;
56

@@ -26,4 +27,16 @@ public static IRepositoryUnitOfWork CreateUnitOfWork(this IFreeSql that)
2627
{
2728
return new RepositoryUnitOfWork(that);
2829
}
30+
31+
/// <summary>
32+
/// 创建基于外部事务的工作单元
33+
/// <para>注意:该工作单元 Commit/Dispose 时不会关闭传入的 transaction,请自行管理 transaction 生命周期</para>
34+
/// </summary>
35+
/// <param name="fsql"></param>
36+
/// <param name="transaction">外部传入的 DbTransaction</param>
37+
/// <returns></returns>
38+
public static IUnitOfWork CreateUnitOfWork(this IFreeSql fsql, DbTransaction transaction)
39+
{
40+
return new ExternalUnitOfWork(fsql, transaction);
41+
}
2942
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
using System;
2+
using System.Data.Common;
3+
using System.Linq;
4+
5+
namespace FreeSql
6+
{
7+
/// <summary>
8+
/// 外部事务适配的工作单元
9+
/// <para>用于适配第三方事务(如 EFCore、ADO.NET 原生事务)给 FreeSql 使用</para>
10+
/// </summary>
11+
public class ExternalUnitOfWork : UnitOfWork, IUnitOfWork
12+
{
13+
private readonly DbTransaction _externalTran;
14+
15+
public ExternalUnitOfWork(IFreeSql fsql, DbTransaction externalTran) : base(fsql)
16+
{
17+
if (externalTran == null) throw new ArgumentNullException(nameof(externalTran));
18+
_externalTran = externalTran;
19+
this._tran = externalTran;
20+
}
21+
22+
#region IUnitOfWork 显式接口实现 (拦截基类行为)
23+
24+
DbTransaction IUnitOfWork.GetOrBeginTransaction(bool isCreate)
25+
{
26+
return _externalTran;
27+
}
28+
29+
void IUnitOfWork.Commit()
30+
{
31+
try
32+
{
33+
_fsql?.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(_tranBefore, "提交(外部)", null));
34+
35+
if (EntityChangeReport != null && EntityChangeReport.OnChange != null && EntityChangeReport.Report.Any())
36+
EntityChangeReport.OnChange.Invoke(EntityChangeReport.Report);
37+
}
38+
finally
39+
{
40+
EntityChangeReport?.Report.Clear();
41+
}
42+
}
43+
44+
void IUnitOfWork.Rollback()
45+
{
46+
try
47+
{
48+
_fsql?.Aop.TraceAfterHandler?.Invoke(this, new Aop.TraceAfterEventArgs(_tranBefore, "回滚(外部)", null));
49+
}
50+
finally
51+
{
52+
EntityChangeReport?.Report.Clear();
53+
}
54+
}
55+
56+
void IDisposable.Dispose()
57+
{
58+
// 不调用 _externalTran.Dispose(),因为生命周期归外部管理
59+
EntityChangeReport?.Report.Clear();
60+
GC.SuppressFinalize(this);
61+
}
62+
63+
#endregion
64+
}
65+
}

0 commit comments

Comments
 (0)