Congratulations to all the winners of April 2013, they have won INR 3400 cash and INR 20147 worth prizes !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 31767 |  Welcome, Guest!   Register  Login
Home > Articles > LINQ > Simple way of using transactions in ADO.NET Entity framework

Simple way of using transactions in ADO.NET Entity framework

1 vote(s)
Rating: 5 out of 5
Article posted by SheoNarayan on 11/30/2011 | Views: 6921 | Category: LINQ | Level: Beginner | Points: 250 red flag


In this article, we shall learn how to use transactions in ADO.NET Entity framework in simplified manner.

Introduction

First thing first, What is transaction ?

As per MSDN, Transactions are groups of database commands that execute as a package. Using a transaction gives your application the ability to abort (roll back) all changes executed from within the transaction if any errors occur during any part of the transaction process. What this necessarily means that if we are executing three SQL commands in a group and if one of them fails, the database will not get affected (eg. if first two commands has executed successfully and the last one failed, the changes made by first two SQL commands will be rolled back and database will not be affected).

What is ADO.NET Entity Framework?

ADO.NET Entity Framework is an object-relational mapping (ORM) framework for the .NET application that can be used to perform Create, Read, Update and Delete operations in the database. It also helps us speedy development as we do not need to write ADO.NET code ourselves. We just need to add an ADO.NET Entity data model and write few lines of code to perform database operations.

Objective

The objective of this article is to demonstrate, how to use transactions in ADO.NET Entity framework. To achieve this, we are going to use TransactionScope class that exists in System.Transactions namespace. To know more about TransactionScope and its use in normal coding, read this article.

Get 500+ ASP.NET web development Tips & Tricks and ASP.NET Online training here.

Using the code

To demonstrate using transactions in ADO.NET Entity Framework, I have created a simple .aspx page with two GridViews and a Button.

<asp:GridView ID="GridView1" runat="server" EnableViewState="false" />

<asp:GridView ID="GridView2" runat="server" EnableViewState="false" />

<asp:Button ID="fdas" runat="server" Text="Save with transaction" OnClick="SaveUsingLinqWithTransaction" />


Two GridViews list records from PersonalDetail and Menu tables (this is the simple table structure) separately. On click of the button, we are calling SaveUsingLinqWithTransaction method and below is the code of this method.

Namespace to use

using System.Transactions;

protected void SaveUsingLinqWithTransaction(object sender, EventArgs e)

{

using (TransactionScope scope = new TransactionScope()) // exists in System.Transactions

{

try

{

using (DemoDatabaseDB db = new DemoDatabaseDB()) // Context object

{

PersonalDetail p = new PersonalDetail()

{

Active = true,

Age = int.MaxValue,

FirstName = "firstnamne",

LastName = "lastname"

};

db.PersonalDetails.AddObject(p);

db.SaveChanges();

DemoDatabaseModel.Menu m = new DemoDatabaseModel.Menu()

{

MenuDescription = "description1",

MenuName = "Menu1Menu1Menu1Menu1Menu1Menu1Menu21",

MenuUrl = "http://www.fundooVideo.com/",

ParentMenuId = 1,

MenuId = 1245

};

 

db.Menus.AddObject(m);

db.SaveChanges();

db.AcceptAllChanges();

}

scope.Complete(); // transaction complete

}

catch (Exception ee)

{

Response.Write(ee.ToString());

}

}

}

 
In the above code snippet, we have instantiated TransactionScope class with using block. It ensures that when we are done with this object, it is disposed so we do not have memory leak problem.

DemoDatabaseDB is my context class of ADO.NET Entity Framework that has also been instantiated with using block. We are first trying to add a PersonalDetail data into the database so we have instantiated that class and set the value, to save this data to the database we have added this object into AddObject method of the PersonalDetails object of the context object and called the SaveChanges() method.

Similarly, we have done the same for the Menu data as well. At last we have called the Complete() method.

Wrapping our ADO.NET Entity Framework commands inside the TransactionScope ensures that all commands executed on the object actually temporarily affects the database and once the .Complete() method is called, these operations are marked as permanent. 

Note that in case you have a AutoIncrement column in the database table and the transactions fails, the auto increment value will increase by 1 every time it fails.

As against the normal ADO.NET Transaction, there is no Rollback() method of the TransactionScope here. Unless you call the Complete() method, the transaction is not treated as complete and all the operations are rolled back automatically.

Is there any other way to achieve the transactions in ADO.NET Entity framework?

Yes, there is one more way to achieve the same thing explained here and Deeraj has written a nice article on this long back.

Thanks for reading and hope this article was useful. 

Keep learning and sharing knowledge on DotNetFunda.com website.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

>> Write Response - Respond to this post and get points
Related Posts

This article deals with using LINQ to Xml in C#.

In this article, we will find the N-th highest salary of employee using LINQ/Lambda.

The article demonstrates the different core concepts of LINQ to XML with an easy console application that will create an XML document dynamically.

Entity Data Model (EDM) is bridge between application and database. LINQ(Language Integated Query) to entity which performs CRUD operations against the Entity Data Model(EDM)

This Article demonstrate the basic functionality of Lambda Expression in C#(Console Application).

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/18/2013 8:33:10 AM