January 2018 : Instructor-led Online Course in ASP.NET Core 2.0. Conducted by Bipin Joshi. Read more...
Registration for January 2018 batch of ASP.NET Core 2.0 instructor-led online course has already started. Conducted by Bipin Joshi. Register today ! Click here for more details.

Passing data from one controller

Wrapping multiple calls to SaveChanges() in a single transaction

When you make any additions, modifications and deletions to an Entity Framework DbSet and call SaveChanges(), EF starts a new transaction and executes all the INSERT, UPDATE and DELETE operations inside that newly created transaction. If the call to SaveChanges() succeeds the underlying transaction is committed, otherwise the transaction is rolled back. In some cases you may want that multiple calls to SaveChanges() be executed in the same transaction. Luckily, Entity Framework 6 provides an easy way to accomplish the same.

Let's assume that you have an Entity Framework data model with Customer entity as shown below:

Now suppose that you wrote the following code to add two Customer records to the database.

NorthwindEntities db = new NorthwindEntities();

Customer obj1 = new Customer();
obj1.CustomerID = "ABCDE";
obj1.CompanyName = "Company 1";
obj1.ContactName = "Contact 1";
obj1.Country = "USA";
db.Customers.Add(obj1);

db.SaveChanges();

Customer obj2 = new Customer();
obj2.CustomerID = "PQRST";
obj2.CompanyName = "Company 2";
obj2.ContactName = "Contact 2";
obj2.Country = "USA";
db.Customers.Add(obj2);

db.SaveChanges();

In this case two calls to SaveChanges() are made. The first call adds the first Customer to the database and the second call adds the other Customer to the database. If the second call to SaveChanges() fails for some reason the first Customer still gets added to the database because each call to SaveChanges() runs in its own transaction.

Now let's modify this code as shown below:

using(NorthwindEntities db = new NorthwindEntities())
{
DbContextTransaction transaction = db.Database.BeginTransaction();

try
{
    //insert a record
    Customer obj1 = new Customer();
    obj1.CustomerID = "ABCDE";
    obj1.CompanyName = "Company 1";
    obj1.ContactName = "Contact 1";
    obj1.Country = "USA";
    db.Customers.Add(obj1);

    //first call to SaveChanges()

    db.SaveChanges();

    //insert another record
    Customer obj2 = new Customer();
    obj2.CustomerID = "PQRST";
    obj2.CompanyName = "Company 2";
    obj2.ContactName = "Contact 2";
    obj2.Country = "USA";
    db.Customers.Add(obj2);

    //second call to SaveChanges()

    db.SaveChanges();

    transaction.Commit();
}
catch
{
    transaction.Rollback();
}
}

Notice that the above code explicitly starts a transaction by calling BeginTransaction() method on the Database property of the data context. The BeginTransaction() returns a DbContextTransaction object which is stored in a local variable. This object is used to either commit or rollback the transaction later in the code.

The code then adds Customer entities as before and calls SaveChanges() after each addition. This time since our code is explicitly creating a transaction, both the calls to SaveChanges() are treated as the part of this transaction. If both the calls to SaveChanges() are successful we call Commit() method of DbContextTransaction object. If any of them fails we call the Rollback() method of DbContextTransaction object.

You can test the above code by setting the CustomerID of the second Customer to a string longer than five characters.

Note:
There is also UseTransaction() method that can be used if you wish to couple EF operations with plain ADO.NET transactions.

That's it for now! Keep coding !!


Bipin Joshi is a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Meditation and Mindfulness to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 29 July 2014


Tags : ADO.NET Data Access C# Visual Studio