tags:

views:

23

answers:

1

I have two entitys: User and UserRole. It is realized as tables in DB and classes with the same names. If I create new user I must create userrole for him. If there is exception during user creation or userrole creation user musn't be created. Question is that I don't know how to set try catch blockes. I have some alternatives:

1)

try
{
  UserDA.BeginTransaction();
  try
  {
    UserDA.Save(newUser);
    UserDA.CommitTransaction();
  }
  catch()
  {
   throw SomeException;
   UserDA.RollbackTransaction();
  }

  UserRoleDA.BeginTransaction();
  try
  {
    UserRoleDA.Save(newUser);
    UserRoleDA.CommitTransaction();
  }
  catch()
  {
   throw SomeException;
   UserRoleDA.RollbackTransaction();
  }
}
catch()
{
  //catch user creation exception
}

2)

UserDA.BeginTransaction();
try
{
  UserDA.Save(newUser);
  UserDA.CommitTransaction();
  UserRoleDA.BeginTransaction();
      try
      {
        UserRoleDA.Save(newUser);
        UserRoleDA.CommitTransaction();
      }
      catch()
      {
       throw SomeException;
       UserRoleDA.RollbackTransaction();
      }
}
catch()
{
  //catch 
  UserDA.RollbackTransaction();
}

May be someone know more correct way.

+2  A: 

The general way of doing this is:

Try{
    StartTransaction
    ...do work...
    CommitTransaction
}
catch(Exception)
{
    RollbackTransaction
}

That way anything thrown while doing work causes the whole transaction to rollback. Only if you reach the end of ...do work... without an exception being thrown does commit get called.

Visage