gpt4 book ai didi

c# - Dapper 异步和事务

转载 作者:行者123 更新时间:2023-11-30 23:09:19 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何在交易中正确使用 Dapper。但我仍然认为我做错了什么。我找到的所有示例都没有使用异步。

有人可以告诉我如何正确地做吗?

class DapperAsyncTransaction
{
private readonly IDbConnection _dbConnection;
private IDbTransaction _dbTransaction;

private IDbConnection Connection => _dbTransaction.Connection;

/// <summary>
/// Constructor
/// </summary>
/// <param name="dbConnection"></param>
public DapperAsyncTransaction(
IDbConnection dbConnection)
{
_dbConnection = dbConnection;
_dbConnection.Open();
_dbTransaction = _dbConnection.BeginTransaction();
}

public async Task Execute()
{
try
{
await Connection.ExecuteAsync(
@"insert into Persons(Name, Surname) values" +
"(@Name, @Surname)",
param: new { Name = "John", Surname = "Doe" },
transaction: _dbTransaction);


_dbTransaction.Commit();
}
catch (Exception)
{
_dbTransaction.Rollback();
}
finally
{
_dbTransaction.Dispose();
_dbTransaction = _dbConnection.BeginTransaction();
}
}
}

最佳答案

只需在启用 TransactionScopeAsyncFlowOption 的事务范围内包装您的数据库访问即可。

public async Task AddPerson(string name, string surname)
{
const string sql = "insert into Persons(Name, Surname) values(@Name, @Surname)";

using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
using (var connection = await _connectionProvider.OpenAsync()) //Or however you get the connection
{
await connection.ExecuteAsync(sql, new{name, surname});
tran.Complete();
}
}

关于c# - Dapper 异步和事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45860502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com