# 分布式事务
同时操作多个数据库,保证事务一致性
//任意表为例:
public partial class Sys_DepartmentController
{
private readonly ISys_DepartmentService _service;//访问业务代码
//构造方法获取第一个数据库对象
private readonly ISys_DepartmentRepository _departmentRepository;
//构造方法获取第二个数据库对象
private readonly ITestDbRepository _testDbRepository;
[ActivatorUtilitiesConstructor]
public Sys_DepartmentController(
ISys_DepartmentService service,
ISys_DepartmentRepository repository,
ITestDbRepository testDbRepository,
IHttpContextAccessor httpContextAccessor
)
: base(service)
{
_service = service;
_departmentRepository = repository;
_testDbRepository = testDbRepository;
}
/// <summary>
/// 分布式事务配置,同时操作多个数据库保证事务一致性
/// </summary>
/// <returns></returns>
[HttpPost, Route("transactionTest")]
public IActionResult TransactionTest()
{
using (var transaction1 = _departmentRepository.DbContext.Database.BeginTransaction())
{
try
{
//第一个数据库的操作
//_departmentRepository.Update/Add操作数据库
_departmentRepository.SaveChanges();// //提交数据库保存
using (var transaction2 = _testDbRepository.DbContext.Database.BeginTransaction())
{
try
{
//第二个数据库操作
//_testDbRepository.Update/Add操作数据库
_testDbRepository.SaveChanges(); //提交数据库保存
//第三个数据库的操作
//using (transaction3 = _xxxDbRepository.DbContext.Database.BeginTransaction())
//{
// try
// {
// 提交第三个数据库事务
// transaction3.Commit();
// }
// catch (Exception)
// {
// transaction3?.Rollback();
// throw;
// }
//}
//提交第三个数据库事务
transaction2.Commit();
}
catch (Exception ex)
{
transaction2.Rollback();
throw ex;
}
}
//提交第一个数据库事务
transaction1.Commit();
}
catch (Exception ex)
{
transaction1.Rollback();
return Content(ex.Message + ex.StackTrace + ex.InnerException);
}
}
return Content("OK");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
← EF事务 EF多表关联或主从明细查询 →