如何使用工作单元和存储库模式回滚事务?
我有一个用户存储库,它负责所有用户数据访问。我还有一个工作单元类来管理我的存储库的连接和事务。如果我的存储库中发生错误,如何有效地回滚我的工作单元类上的事务?
在我的 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;
}
}
我希望找出最好的方法。
* 更新 * 在对工作单元模式进行了更多研究之后,我认为我在示例中使用它完全错误。
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. I'm using Dapper for 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Dapper 支持
TransactionScope
,它提供了一个Complete()
方法来提交事务,如果您不调用Complete()
事务将被中止。Dapper supports
TransactionScope
, which provides aComplete()
method to commit the transaction, if you don't callComplete()
the transaction is aborted.