【问题标题】:how i can use transactions in dapper C#我如何在 Dapper C# 中使用事务
【发布时间】:2018-01-26 09:20:36
【问题描述】:

我如何在 Dapper C# 中使用事务。 我的问题是我需要锁定一个表,所以我使用 BeginTransaction,我执行其他事务,直到我完成这些事务,我可以使用我向您展示的代码进行提交。它可以做到,但是当我同时收到 2 笔交易时,一笔交易并不能很好地关闭连接。谢谢。

我想这样做,但要使用 dapper。

public int UpdateStan(PosDTO posParams)
{
    int result = cnn.Execute(new Templates.Queries.upDateStan().TransformText(), new

    {
        id_merchant = posParams.idMerchant
    }, transaction);
    transaction.Commit();
    cnn.Close();
    cnn.Dispose();
    return result;

}

public BatchStanDTO getBatchStan(PosDTO posDto)
{
    cnn = _sodexoSource.Create();
    cnn.Open();
    transaction = cnn.BeginTransaction();
    return cnn.Query<BatchStanDTO>(new Templates.Queries.getBatchStan().TransformText(), new { idMerchant = posDto.idMerchant }, transaction).FirstOrDefault();

}

public void rollbackTran()
{
    try
    {
        transaction.Rollback();
    }
    catch (Exception ex)
    {

    }
}

【问题讨论】:

  • 根据您的帖子,您的要求非常不清楚。这看起来已经像 Dapper 了。您遇到了什么具体问题?
  • 我认为 TransactionScope 包裹在您的代码中会起作用。
  • 我想使用 dapper Wrapper,但我无法获得像 cnn.Open() 这样的连接对象; ,好吧,我不明白连接器在哪里打开。谢谢
  • 似乎是一些不错的建议here
  • 当您在代码中使用cnn.Query&lt;T&gt;cnn.Execute 时,cnn 是您的SQLConnection 对象。除了 Dapper 为您提供的额外方法之外,您还可以执行所有正常的 SqlConnection 操作。

标签: c#


【解决方案1】:

您可以根据需要创建任意数量的事务,并使用 using 语句加入这些事务。 从当前连接中获取您的交易并执行类似的操作

using(var tranB= connection.BeginTransaction())
{
    using(var tran = connection.BeginTransaction()) {
    try {
        // multiple operations involving connection and tran here

            tran.Commit();
        } catch {
            tran.Rollback();
            throw;
        }
    }
    tranB.Commit();
}

【讨论】:

    【解决方案2】:

    您也可以使用 Dapper Transaction。它与 Dapper 相同,但在代码方面扩展了您可能更喜欢的事务:

    using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
    {
        connection.Open();
        
        using (var transaction = connection.BeginTransaction())
        {
            // Dapper
            var affectedRows1 = connection.Execute(sql, new {CustomerName = "Mark"}, transaction: transaction);
            
            // Dapper Transaction
            var affectedRows2 = transaction.Execute(sql, new {CustomerName = "Mark"});
    
            transaction.Commit();
        }
    }
    

    代码取自dapper-tutorial

    【讨论】:

      猜你喜欢
      • 2015-02-28
      • 2020-06-02
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      相关资源
      最近更新 更多