How to: Manage EntityClient Transactions (Entity Framework)

[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

This topic shows how to use a TransactionScope to make sure that all code that processes sales orders will complete without errors or be rolled back. The benefits of using System.Transactions include a pattern for transactions that applies to all transaction-capable APIs in the .NET Framework and the capability of handling both local and distributed transactions transparently.

The use of TransactionScope resembles a transaction-processing monitor context in which there is no explicit call to commit the data to storage. The code syntax shown earlier includes calling the method Complete to collect all the results of processing. If all procedures complete as expected, the data will commit to storage. Any negative result will roll back the transaction. The call to Complete signals the end of processing and calls in the results.

using(TransactionScope transactionScope = new TransactionScope()) 

  using(EntityConnection con = new EntityConnection(connstring)) 

    EntityCommand cmd1 = con.CreateCommand();
    cmd1.CommandText = "SELECT VALUE so FROM SalesOrders AS so";

    DbDataReader r1 = cmd1.ExecuteReader();

    While(r1.Read()) {

      if(NeedToProcessLines(r1)) {
        EntityCommand cmd2 = con.CreateCommand();
        cmd2.CommandText = 
              "SELECT NAVIGATE(ol, OrderLine_Product).ProductName, ol.Quantity " +
              "FROM OrderLines AS ol WHERE ol.OrderID = @orderID";

        DbDataReader r2 = cmd2.ExecuteReader();

        // process r2