【发布时间】:2017-01-19 04:34:31
【问题描述】:
假设我有一个像下面这样的类,我怎样才能实现使 MasterMethod (MethodA, MethodB, and MethodC) 中的所有调用方法继承从 MasterMethod 实例化的 MySqlTransaction 对象?
private MySqlConnection OpenConnection() {
try {
MySqlConnection DbConn = new MySqlConnection("~connectionstring");
DbConn.Open();
return DbConn;
} catch(Exception Ex) {
throw Ex;
}
}
public void MasterMethod() {
using(MySqlConnection DbConn = OpenConnection()) {
using(MySqlTransaction DbTrans = DbConn.BeginTransaction()) {
try {
MethodA();
MethodB(Param1);
MethodC(Param1, Param2);
DbTrans.Commit();
} catch(Exception Ex) {
DbTrans.Rollback();
throw Ex;
}
}
}
}
public void MethodA() {
using(MySqlConnection DbConn = OpenConnection()) {
using(MySqlTransaction DbTrans = DbConn.BeginTransaction()) {
try {
// Lots and Lots of things to do
DbTrans.Commit();
} catch(Exception Ex) {
DbTrans.Rollback();
throw Ex;
}
}
}
}
public void MethodB(int Param1) {
using(MySqlConnection DbConn = OpenConnection()) {
using(MySqlTransaction DbTrans = DbConn.BeginTransaction()) {
try {
// Lots and Lots of things to do
DbTrans.Commit();
} catch(Exception Ex) {
DbTrans.Rollback();
throw Ex;
}
}
}
}
public void MethodC(string Param1, string Param2) {
using(MySqlConnection DbConn = OpenConnection()) {
using(MySqlTransaction DbTrans = DbConn.BeginTransaction()) {
try {
// Lots and Lots of things to do
DbTrans.Commit();
} catch(Exception Ex) {
DbTrans.Rollback();
throw Ex;
}
}
}
}
在我当前的架构中,查询会在特定 Method 的块到达其末尾后立即提交,而不是等待 MasterMethod 的 try 块最底部的 DbTrans.Commit()。
我怎样才能使它 (the MySqlTransaction Object) 的行为方式必须等待所有 3 个嵌套/调用方法 (MethodA, MethodB, MethodC) 才能提交(或回滚)对数据库的更改?
【问题讨论】:
标签: c# mysql methods transactions nested