This documentation is archived and is not being maintained.

How to: Manage Transactions in the Entity Framework

This topic provides an example of how to define a transaction that coordinates making changes to objects in an object context with other external operations. For more information, see Managing Connections and Transactions.

The example in this topic is based on the AdventureWorks Sales Model. To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedure in How to: Use the Entity Data Model Wizard. You must also have Microsoft Windows Message Queuing installed.


This example defines a TransactionScope. The TransactionScope ensures that changes to objects in the object context are coordinated with a message queue. The Entity Framework uses this transaction when it saves changes to the database. When an UpdateException occurs, the operation is retried up to two times. When the operation succeeds, the changes in the object context are accepted. For more information, see Managing Connections and Transactions.

This example uses a long-running object context, which is disposed after the transaction succeeds or after all retries have been attempted.

using System;
using System.Linq;
using System.Data;
using System.Data.Objects;
using System.Messaging;
using System.Transactions;

namespace ObjectServicesConceptsCS
    class TransactionSample
        public static void EnlistTransaction()
            int retries = 3;
            string queueName = @".\Fulfilling";

            // Define variables that we need to add an item.
            short quantity = 2;
            int productId = 750;
            int orderId = 43680;

            // Define a long-running object context.
            AdventureWorksEntities context
                = new AdventureWorksEntities();

            bool success = false;

            // Wrap the operation in a retry loop.
            for (int i = 0; i < retries; i++)
                // Define a transaction scope for the operations.
                using (TransactionScope transaction = new TransactionScope())
                        // Define a query that returns a order by order ID.
                        SalesOrderHeader order =
                        ("it.SalesOrderID = @id", new ObjectParameter(
                         "id", orderId)).First();

                        // Load items for the order, if not already loaded.
                        if (!order.SalesOrderDetails.IsLoaded)

                        // Load the customer, if not already loaded.
                        if (!order.ContactReference.IsLoaded)

                        // Create a new item for an existing order.
                        SalesOrderDetail newItem = SalesOrderDetail.CreateSalesOrderDetail(
                            0, 0, quantity, productId, 1, 0, 0, 0, Guid.NewGuid(), DateTime.Today);

                        // Add new item to the order.

                        // Save changes pessimistically. This means that changes 
                        // must be accepted manually once the transaction succeeds.

                        // Create the message queue if it does not already exist.
                        if (!MessageQueue.Exists(queueName))

                        // Initiate fulfilling order by sending a message.
                        using (MessageQueue q = new MessageQueue(queueName))
                            System.Messaging.Message msg =
                                new System.Messaging.Message(String.Format(
                                    "<order customerId='{0}'>" +
                                    "<orderLine product='{1}' quantity='{2}' />" +
                                    "</order>", order.Contact.ContactID,
                                newItem.ProductID, newItem.OrderQty));

                            // Send the message to the queue.

                        // Mark the transaction as complete.
                        success = true;
                    catch (Exception ex)
                        // Handle errors and deadlocks here and retry if needed.
                        // Allow an UpdateException to pass through and 
                        // retry, otherwise stop the execution.
                        if (ex.GetType() != typeof(UpdateException))
                            Console.WriteLine("An error occured. "
                                + "The operation cannot be retried."
                                + ex.Message);
                        // If we get to this point, the operation will be retried.
            if (success)
                // Reset the context since the operation succeeded.
                Console.WriteLine("The operation could not be completed in "
                    + retries + " tries.");

            // Dispose the object context.

See Also