如何使用 Dapper 跨多个方法调用使用事务?
How to use transaction across multiple method calls with Dapper?
我需要包装一些对正在执行 async
更新和插入我的数据库的方法的调用。所有方法都将此模式用于 运行 代码:
using (IDbConnection conn = Connection)
{
conn.Open();
//TODO: Table item quantity for the QTYALLOC field
var sql = //sql statement;
int x = await conn.ExecuteAsync(sql);
return x > 0;
}
现在所有的方法return一个boolean
。我想将调用包装在事务中并提交或回滚
await [InsertRecord];
//add the audit record
var addAudit = await [Insert Audit Record];
var updateOrd = await [Update Record]
var changePickStatus = await [Update Record]
if (locs.First().QTYTOTAL - ord.QTYPICKED <= 0)
{
await [Delete Record]; //delete the record
}
else
{
//decrement the quantity for the location and update.
locs.First().QTYTOTAL -= ord.QTYPICKED;
await [Update Record]
}
我将对方法的调用放在方括号 [] 中。现在每次调用 returns 一个 boolean
来指示它是成功还是失败,我想将所有这些调用包装在一个事务中以根据每次调用的结果提交或回滚。如果可以的话,我不想将所有 SQL 语句放入一个大型调用中,它们又长又复杂。我可以将事务传递给每个方法调用并将其应用于每个 ExecuteAsync
操作吗?如果是这样,我将从该方法返回什么来指示成功或失败?
您可以在每个方法调用中注入 connection/transaction 作为参数。
以下是一种伪代码(语法可能不准确):
using (IDbConnection conn = Connection)
{
using(var transaction = conn.BeginTransaction())//Begin here
{
var addAudit = await [YourMethod(conn)];//Inject as parameter
if(addAudit == false)
transaction.Rollback();//Rollback if method call failed
...
...
//Repeat same pattern for all method calls
...
transaction.Commit();//Commit when all methods returned success
}
}
更好的解决方案是使用Unit Of Work。但是,只有在更广泛的层面上实施它才有价值。
我需要包装一些对正在执行 async
更新和插入我的数据库的方法的调用。所有方法都将此模式用于 运行 代码:
using (IDbConnection conn = Connection)
{
conn.Open();
//TODO: Table item quantity for the QTYALLOC field
var sql = //sql statement;
int x = await conn.ExecuteAsync(sql);
return x > 0;
}
现在所有的方法return一个boolean
。我想将调用包装在事务中并提交或回滚
await [InsertRecord];
//add the audit record
var addAudit = await [Insert Audit Record];
var updateOrd = await [Update Record]
var changePickStatus = await [Update Record]
if (locs.First().QTYTOTAL - ord.QTYPICKED <= 0)
{
await [Delete Record]; //delete the record
}
else
{
//decrement the quantity for the location and update.
locs.First().QTYTOTAL -= ord.QTYPICKED;
await [Update Record]
}
我将对方法的调用放在方括号 [] 中。现在每次调用 returns 一个 boolean
来指示它是成功还是失败,我想将所有这些调用包装在一个事务中以根据每次调用的结果提交或回滚。如果可以的话,我不想将所有 SQL 语句放入一个大型调用中,它们又长又复杂。我可以将事务传递给每个方法调用并将其应用于每个 ExecuteAsync
操作吗?如果是这样,我将从该方法返回什么来指示成功或失败?
您可以在每个方法调用中注入 connection/transaction 作为参数。
以下是一种伪代码(语法可能不准确):
using (IDbConnection conn = Connection)
{
using(var transaction = conn.BeginTransaction())//Begin here
{
var addAudit = await [YourMethod(conn)];//Inject as parameter
if(addAudit == false)
transaction.Rollback();//Rollback if method call failed
...
...
//Repeat same pattern for all method calls
...
transaction.Commit();//Commit when all methods returned success
}
}
更好的解决方案是使用Unit Of Work。但是,只有在更广泛的层面上实施它才有价值。