开发者

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

开发者 https://www.devze.com 2023-02-13 04:40 出处:网络
I am working on a existing system(asp.net 2, ms sql server 2005) where repository pattern is implemented like:

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 开发者_如何学JAVAgive 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 ...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号