how to implement Unit Of Work just using just TransactionScope and sqlconnections

六月ゝ 毕业季﹏ 提交于 2019-12-23 02:43:15

问题


I am working on a existing system(asp.net 2, ms sql server 2005) where repository pattern is implemented like:

IMyRepository
{
  void add(object o);
  int update(object obj);
  int delete(object obj);
  IList<T> getAll();
  IList<T> getByDate(DateTime date);
....
}

The system has 3 different products. So We have different repository for each product. As the requirement changes over time, we need to implement Unit Of Work pattern for business process level transaction.
We don't have any ORM.(actually we don't have the permission or time to implement it now) Can anyone give me a clear guideline how to implement Unit Of Work just using just TransactionScope and sqlconnections.

Plz mention how to close Sqlconnections quickly and efficiently(as it has large number of users).
The unit of work pattern is new thing to me.
thanks in advance ...


回答1:


Well, in your unit of work pattern you have a call to Commit() and/or Rollback(). With TransactionScope, you call Complete() or nothing at all, which does the rollback.

using(TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
{
  // do your gets inside of supressed TransactionScopes:
  using (new TransactionScope(TransactionScopeOption.Suppress))
  {
    myRep.GetAll();
  }

  // do your updates
  myRep.Update();

  // no errors, so commit
  ts.Complete();

  // Close db connections
  myConn.Close();
}

Surround the whole thing with a try catch and you'll be all setup. If you get any exceptions, ts.Complete() is never called and your db changes are rolled back. Just remember to reset your connections before you start the transactionscope, and right after you commit or rollback.



来源:https://stackoverflow.com/questions/5079123/how-to-implement-unit-of-work-just-using-just-transactionscope-and-sqlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!