开发者

.net, do you get a transaction object?

Working with SQL / ADO, got me thinking about something that I think should logically be included with the .net framework, and I was wondering if such a thing exists, let me explain.

Is there an object that is essentially a transaction manager, that you pass commands (work items) to and at the same I would imagine it would be necessary also pass the rollback actions for each work item in the transaction.

For example

Lets say I wanted to perform the following actions:

  1. Create a folder
  2. Create a file in this folder
  3. Perform some other misc tasks like editing reg keys, or really action you can think of that can be rolled back.

Now currently if something fails, I need to manually implement a roll back strategy, so perhaps a way exists to manage these work items as a transaction using oob .net functionality?

My considerations are that it would be asking a lot to have items rollback automatically, but having the ability to manually control what happens during a rollback per work item, seems practical.

Another thing is what Microsoft have done with LINQ is really great, effectively having SQL like queries for all kinds of stuff, not only for SQL tables. So perhaps there is some transaction model with LI开发者_StackOverflowNQ?

Thanks, if you know of anything like this?


You can use the TransactionScope class to begin a transaction, but any actions you take inside that transaction have to be "transaction aware" and know how to compensate if the transaction is rolled back.

Brent VanderMeide did a two-part series on dnrTV on how to write classes that know about TransactionScope. Here's part 1, and here's part 2.


Normally transactions in this sense imply DB IO, and not file system operations. In ADO.Net 2.0, you would do something like the code below.

For other types of transactions, I would suggest looking into the MS DTC (Distributed Transaction Coordinator). This will allow your transactions to span different machines, and I also believe that allows you to enlist custom actions to be rolled back.

I hope this helps.

using (SqlConnection connection =
            new SqlConnection(connectionString))
{
    SqlCommand command = connection.CreateCommand();
    SqlTransaction transaction = null;

    try
    {
        // BeginTransaction() Requires Open Connection
        connection.Open();

        transaction = connection.BeginTransaction();

        // Assign Transaction to Command
        command.Transaction = transaction;

        // Execute 1st Command
        command.CommandText = "Insert ...";
        command.ExecuteNonQuery();

        // Execute 2nd Command
        command.CommandText = "Update...";
        command.ExecuteNonQuery();

        transaction.Commit();
    }
    catch
    {
        transaction.Rollback();
        throw;
    }
    finally
    {
        connection.Close();
    }
} 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜