[英]How do I rollback a transaction using Unit of Work and Repository patterns?
I have a user repository, which does all the user data access. 我有一个用户存储库,它可以访问所有用户数据。 I also have a unit of work class that manages the connection and transaction for my repositories.
我还有一个工作类单元,用于管理我的存储库的连接和事务。 How do I effectively rollback a transaction on my unit of work class, if an error happens within my repository?
如果我的存储库中发生错误,如何在我的工作单元上有效地回滚事务?
Create method on my UserRepository. 在我的UserRepository上创建方法。 I'm using Dapper for DataAccess.
我正在使用Dapper进行DataAccess。
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.
}
I pass both the connection and transaction that were created in my unit of work constructor to my repositories. 我将在我的工作单元构造函数中创建的连接和事务传递给我的存储库。 Below is a property on my unit of work class.
以下是我工作单位的财产。
public UserRepository UserRepository
{
get
{
if (this._userRepository == null)
this._userRepository =
new UserRepository(this._connection, this._transaction);
return this._userRepository;
}
}
I'm hoping to figure out the best approach. 我希望找到最好的方法。
* Update * After doing more research into the unit of work pattern I think I am using it completely wrong in my example. *更新*在对工作单元模式进行更多研究后,我认为我在我的例子中使用它完全错误。
Dapper supports TransactionScope
, which provides a Complete()
method to commit the transaction, if you don't call Complete()
the transaction is aborted. Dapper支持
TransactionScope
,它提供了一个Complete()
方法来提交事务,如果你没有调用Complete()
,事务就会被中止。
using (TransactionScope scope = new TransactionScope())
{
//open connection, do your thing
scope.Complete();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.