开发者

transactions using C# to update a database

I'm doing a multi-layer MVVM WPF application, which is connected to an Oracle database. I need some explanations about TransactionScope. Consider the following example:

using (TransactionScope ts = new TransactionScope())
{
   ...
   bank.setID(BankName, Branch);

   check.addCheck(check);
   ...
   ts.Complete();
}

This code is for explanation only: bank.setID() updates a record, while add开发者_如何学GoCheck actually inserts a record. I couldn't figure out how to test this. I wanted to execute the update and shutdown of the database before inserting with the second method, and then check to see if the update is rolled back. Is this already right? Am I on the right track ? Is this the purpose of TransactionScope?

Thanks in advance


Edit: I wasn't sure at first if you understood DB transactions, so here's a very short description:

TransactionScope is designed to wrap a database transaction with a mechanism that is exception safe.

You use it to wrap a set of operations that should be atomic with a transaction, so if you fail on one update, all of the DB actions within that transaction get rolled back.

You use it in a using block so that if your code throws an exception, the transaction gets rolled back, instead of committed to the database.

I wanted to execute the update and shutdown the database before inserting with the second method, and then check to see if the update is rolled back ... Am I on the right track ?

Yep. Your code should already handle it:

  • If the DB is shut down before addCheck does an insert, then the insert should throw an exception
  • Since an exception gets thrown, Complete should never get called
  • The finally block should automatically roll back the transaction when the (hidden) finally block is reached, and Complete hasn't been called

I couldn't figure out how to test this

If you would like to write a unit test for your code, then I wouldn't suggest the "take the DB offline in the middle of execution" approach.

Instead, I'd suggest making your DB logic flexible enough to point at different DBs. Then, either remove the table or some of the columns that addCheck inserts to. Try to set up your DB so that setID succeeds, but addCheck fails.


TransactionScope is well documented. MSDN it.

to test how it works, no need to take database offline. use this snippet:

using (TransactionScope ts = new TransactionScope())
        {
           try
              {
              ...
               bank.setID(BankName, Branch);
               throw new System.InvalidOperationException("sht happens");
               check.addCheck(check);
               ...
               ts.Complete();
              }
          catch
              {
               //catch the exception
               //ts.Complete() is not called, thus update/insert rollbacks
              }
        }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜