Transactions 如何使用Dapper跨多个方法调用使用事务?
我需要包装一些对正在进行Transactions 如何使用Dapper跨多个方法调用使用事务?,transactions,dapper,Transactions,Dapper,我需要包装一些对正在进行async更新并插入到数据库中的方法的调用。所有方法都使用此模式来运行代码: using (IDbConnection conn = Connection) { conn.Open(); //TODO: Table item quantity for the QTYALLOC field var sql = //sql statement;
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;
}
现在所有的方法都返回一个布尔值。我想将调用包装在事务中,然后提交或回滚
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]
}
wait[InsertRecord];
//添加审核记录
var addAudit=等待[插入审计记录];
var updateOrd=await[更新记录]
var changePickStatus=等待[更新记录]
如果(locs.First().QTYTOTAL-ord.QTYPICKED,则可以将连接/事务作为参数注入每个方法调用中
以下是一种伪代码(语法可能不准确):
更好的解决方案是使用。但是,只有在更广泛的层面上实现它时,这才有价值。我使用了一个连接,然后打开它,将事务添加到打开的连接中,并将连接和事务传递到每个方法中。它似乎可以工作,但需要更多的测试来确保其成功。谢谢s
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
}
}