.net, do you get the transaction object?

Working with SQL / ADO made me think about what, in my opinion, should logically be included in the .net structure, and I was wondering if such a thing exists, let me explain.

Is there an object that is essentially a transaction manager that transmits commands (work items), and at the same time, I would suggest that you also need to perform rollback actions for each work item in the transaction.

for example

Suppose I wanted to do the following:

  • Create a folder
  • Create a file in this folder
  • Perform some other tasks, such as editing reg keys or really an action that you can think of that can be thrown back.

Now, if something fails, I need to manually implement the rollback strategy, so maybe there is a way to manage these work items as a transaction using oob.net functions?

My considerations are that he will ask a lot about the failure of the elements automatically, but the possibility of manual control of what happens during the rollback to the work item seems practical.

Another thing that Microsoft has done with LINQ is really great, effectively having SQL queries for all kinds of things, not just SQL tables. So maybe there is some kind of transaction model with LINQ?

Thanks if you know something like this?

+6
source share
2 answers

You can use the TransactionScope class to start a transaction, but any actions taken inside this transaction must be "transactional" and know how to compensate for the return of the transaction.

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

+5
source share

Typically, transactions in this sense imply DB IO, 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 exploring MS DTC (Distributed Transaction Coordinator). This will allow your transactions to spread across different machines, and I also believe that it allows you to use canceled user actions.

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
source share

All Articles