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