Home > DeveloperSection > Articles > Transaction in code first approach in entity framework

Transaction in code first approach in entity framework


ASP.Net ASP.Net 
Ratings:
0 Comment(s)
 2701  View(s)
Rate this:

Transaction in code first approach in entity framework

In this article describe the concept of transaction in code first approach in entity framework. Here we give the example of transaction in code first approach in entity framework.

In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes. When you execute another such operation a new transaction is started. Entity Framework enable you to manage your own transactions. Earlier we were using System.Transactions.dll to handle transactions in Entity Framework using TransactionScope. Entity Framework uses this transaction to save changes to the database. When the operation succeeds, the changes in the object context are accepted. When an Exception occurs while updating, the operation is performed up to two times.

Syntax

using (TransactionScope scope = new TransactionScope())

            {

                //your code Here

            } 

There are two important methods of transaction in entity framework:

Database.BeginTransaction()

 An easier method for a user to start and complete transactions themselves within an existing ‘DbContext’ - allowing several operations to be combined within the same transaction and hence either all committed or all rolled back as one. It also allows the user to more easily specify the isolation level for the transaction.

Database.UseTransaction()

Which allows the ‘DbContext’ to use a transaction which was started outside of the Entity Framework.

Let’s we create an example and understand by the example:

From the visual studio create new console application:

Transaction in code first approach in entity framework

If entity framework does not installed you will be from the following option:

There are two methods by command and by go to the option:

Right click solution explorer and click on ‘Manage NuGet Packages… ‘and install ‘Entity Framework’.

Transaction in code first approach in entity framework

Create the class Customer, Order and PurchaseOrder context class:

public class Customer

    {

        public int CustomerID { getset; }

        public string ContactName { getset; }

        public string Address { getset; }

        public string City { getset; }

        public string State { getset; }

        public string Country { getset; }

        public List<Order> Orders { getset; }

    } 

public class Order

    {

        public int OrderID { getset; }

        public DateTime OrderDate { getset; }

        public DateTime RequiredDate { getset; }

        public int Quantity { getset; }

        public decimal UnitPrice { getset; }

        public int CustomerID { getset; }

    } 

public class PurchaseOrderContext : DbContext

    {

        public PurchaseOrderContext()

            : base("DBConnectionString")

        { }

 

        public PurchaseOrderContext(DbConnection CN, bool ownContext)

            : base(CN, ownContext)

        {

 

        }

 

        public DbSet<Customer> Customers { getset; }

        public DbSet<Order> Orders { getset; }

    }

 

We create the connection string in app.config file:

<connectionStrings>

      <add connectionString="Data Source=ADMIN-PC\SQLEXPRESS;Initial Catalog=PurchaseOrderDB; Integrated Security=true;" name="DBConnectionString"providerName="System.Data.SqlClient"/>

    </connectionStrings>

 

Let’s we create main program and write to code save data and fetch data:

class Program

    {

        static void Main(string[] args)

        {

            UseTransactionTest();

            Console.ReadKey();

        }

        public static void UseTransactionTest()

        {

            PurchaseOrderContext dataContext = new PurchaseOrderContext();

            dataContext.Customers.Add(new Customer()

            {

                ContactName = "Mr. Atul",

                Address = "Civil Lines",

                City = "Allahabad",

                State = "Uttar Pradesh",

                Country = "India",

            });

            dataContext.SaveChanges();

            var query = from cust in dataContext.Customers

                        select cust;

            foreach (var cust in query)

            {

                Console.WriteLine("Customer ID: "+cust.CustomerID + "  Name: " + cust.ContactName);

            }

           

        }

    }

 

Run the application then create the database Transaction in code first approach in entity framework

 

Transaction in code first approach in entity framework

Now let’s use the ‘UseTransaction()’ method in our method ‘UseTransactionTest()’ in our program. Now you first add the ‘System.Configuration.dll’ in our project to access the connection string programmatically.

 

public static void UseTransactionTest()

        {

            using (SqlConnection CN = newSqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString))

            {

                CN.Open();

                using (SqlTransaction trans = CN.BeginTransaction())

                {

                    try

                    {

                        //You can do some Command Object Coding!!

                        using (PurchaseOrderContext dataContext = newPurchaseOrderContext(CN, false))

                        {

                            dataContext.Database.UseTransaction(trans);

                            dataContext.Customers.Add(new Customer()

                            {

                                ContactName = "Mr. Atul",

                                Address = "Civil Lines",

                                City = "Allahabad",

                                State = "Uttar Pradesh",

                                Country = "India",

                            });

                            dataContext.SaveChanges();

                        }

                        trans.Commit();

                    }

                    catch (Exception ex)

                    {

                        trans.Rollback();

                        Console.WriteLine(ex.InnerException);

                    }

                }

            }

            PurchaseOrderContext dataContextFetch = new PurchaseOrderContext();

            var query = from cust in dataContextFetch.Customers

                        select cust;

            foreach (var cust in query)

            {

                Console.WriteLine(cust.CustomerID + "----" + cust.ContactName);

            }

      }

 

In the above method, we are inserting a record into Customers table. We have started and opened the connection and we have forced the Data Context of Entity Framework to use this connection by calling the constructor of our PurchaseOrderConetxt class.

If everything goes well, the transaction will be committed, else it will be rollback (see the code above).

Now let’s make BeginTransaction of Entity framework. Add another method in the following code:

public static void BeginTransactionTest()

        {

            using (PurchaseOrderContext dataContext = new PurchaseOrderContext())

            {

                using (var trans = dataContext.Database.BeginTransaction())

                {

                    try

                    {

                        dataContext.Customers.Add(new Customer()

                        {

                            ContactName = "Mr. Atul",

                            Address = "Civil Lines",

                            City = "Allahabad",

                            State = "Uttar Pradesh",

                            Country = "India",

                        });

                        dataContext.SaveChanges();

                        trans.Commit();

                    }

                    catch (Exception ex)

                    {

                        trans.Rollback();

                        Console.WriteLine(ex.InnerException);

                    }

                }

            }

 

In the above method, context has its own connection and it’s started the transaction.

 

In this article, I hope that you are satisfy above article of transaction in code first approach in entity framework.


Don't want to miss updates? Please click the below button!

Follow MindStick