c# - 如何使用工作单元和存储库模式回滚事务?

标签 c# ado.net transactions repository unit-of-work

我有一个用户存储库,它负责所有用户数据访问。我还有一个工作单元类来管理我的存储库的连接和事务。如果我的存储库中发生错误,如何有效地回滚工作单元类上的事务?

在我的 UserRepository 上创建方法。我正在使用 Dapper 进行数据访问。

try
{
    this.Connection.Execute("User_Create", parameters, this.Transaction, 
        commandType: CommandType.StoredProcedure);
}
catch (Exception)
{
    //Need to tell my unit of work to rollback the transaction.                
}

我将在工作单元构造函数中创建的连接和事务传递到我的存储库。下面是我的工作单元类的一个属性。

public UserRepository UserRepository
{
    get
    {
        if (this._userRepository == null)
            this._userRepository = 
                new UserRepository(this._connection, this._transaction);
        return this._userRepository;
    }
}

我希望找出最好的方法。

* 更新 * 在对工作单元模式进行了更多研究之后,我认为我在示例中使用它完全错误。

最佳答案

Dapper 支持 TransactionScope ,它提供了一个 Complete() 方法来提交事务,如果您不调用 Complete() 事务就会中止。

using (TransactionScope scope = new TransactionScope())
{
   //open connection, do your thing
   scope.Complete();
}

关于c# - 如何使用工作单元和存储库模式回滚事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7541063/

相关文章:

C# COM 服务器到 C# COM 客户端使用 CoCreateInstance

ado.net - 如何使用 ADO.NET 读取 .XLSX (Excel 2007) 文件?我发现 "Could not find installable ISAM"-错误

c# - 与 SMSS 相比,从 ADO.NET 执行具有相同查询计划的相同查询需要大约 10 倍的时间

php - 为什么每一行提交交易这么慢?

Spring hibernate 手动提交

c# - 从下拉列表中检索选定的枚举

c# - 应该关闭远程 Powershell session 吗?

firebase - Firestore 事务失败,出现 "Transaction failed all retries"

c# - 如何对该方法的 catch block 进行单元测试?

c# - 当数据读取器可能没有特定列时要检查什么?