Search
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Fri, 31-Oct-2014 Authors
All Time Authors
Sourav.Kayal
39750
SheoNarayan
38050
Niladri.biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

Transaction in ADO.NET Entity Framework

Deeraj
Posted by under ADO.NET category on for Beginner level | Views : 22847 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 4.29 out of 5
7 vote(s)
This article gives an insight into how to perform transactions using ADO.NET Entity Framework. This article is being authored for it to be at a very basic level and will not consider database isolation levels. Also, this article assumes that readers are already aware of ADO.NET Entity Framework.

 Download source code for Transaction in ADO.NET Entity Framework


Introduction

 

This article gives an insight into how to perform transactions using ADO.NET Entity Framework. This article is being authored for it to be at a very basic level and will not consider database isolation levels. Also, this article assumes that readers have a prior knowledge of ADO.NET Entity Framework.


ADO.NET Entity Framework's Transaction in Action:


Lets not dig too much into the theory and lets jump in for a demonstration with steps and explanation.

 

For the demonstration to keep simple, let’s create a console application. After all, we just need to know how to perform transactions using ADO.NET Entity framework.

 

As always, for any DB oriented application, first step is to create a database. Lets create our brand new database.

 

Create a new database, ADONETEntityTransactionTest - Steps to create database were ignored.

 

Run the following script that will create new two tables that we will use as part of this demonstration. I call them Category and Product.

 

USE [ADONETEntityTransactionTest]

GO

 

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

SET ANSI_PADDING ON

GO

 

CREATE TABLE [dbo].[Category](

      [CategoryID] [int] IDENTITY(1,1) NOT NULL,

      [CategoryName] [varchar](50) NULL,

 CONSTRAINT [PK_Category] PRIMARY KEY CLUSTERED

(

      [CategoryID] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]

 

GO

 

SET ANSI_PADDING OFF

GO

 

 

USE [ADONETEntityTransactionTest]

GO

 

/****** Object:  Table [dbo].[Product]    Script Date: 05/07/2010 17:42:43 ******/

SET ANSI_NULLS ON

GO

 

SET QUOTED_IDENTIFIER ON

GO

 

SET ANSI_PADDING ON

GO

 

CREATE TABLE [dbo].[Product](

      [ProductID] [int] IDENTITY(1,1) NOT NULL,

      [ProductName] [varchar](50) NULL,

      [Description] [varchar](50) NULL,

      [CategoryID] [int] NULL,

 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED

(

      [ProductID] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]

 

GO

 

SET ANSI_PADDING OFF

GO

 

ALTER TABLE [dbo].[Product]  WITH CHECK ADD  CONSTRAINT [FK_Product_Category] FOREIGN KEY([CategoryID])

REFERENCES [dbo].[Category] ([CategoryID])

GO

 

ALTER TABLE [dbo].[Product] CHECK CONSTRAINT [FK_Product_Category]

GO

 

After following the above steps the object explorer of SSMS 2005/2008 should be something like the following screenshot. Notice we have two tables created with referential integrity.

 

 

And now,

 

Let’s start creating a new console application project, and call it ADONETEntityFrameworkTransaction

 

 

After creating the project, right click on the project and choose add -> new item. This will popup the following screen. Choose 'ADO.NET Entity Data Model' and name it as ‘MyEntityModel.edmx’

 

 

Follow the steps below to choose the database server, database and tables for use by our MyEntityModel.EDMX.

 

 

Click Next to see the screen below.

 

Click on ‘New Connection…’ to proceed

 

 

In the following screen, choose the SQL Server and the Database that we created at the start of this article to work with.

 

 

Click OK to see the following screen.

 

 

In the above screen check the check box ‘Save entity connection settings in App.Config as:’ and give the name as ‘ADONETEntityTransactionTestEntities’. Click Next. This action will create a connection string in the App.config

 

In the following screen choose the two tables (Category and Product) we created.

 

 

Click finish. The solution at this stage should be something equal to the one that's shown below.

 

 

Notice, in the App.config file, we have the following connection string created

<?xml version="1.0" encoding="utf-8"?>

<configuration>

  <connectionStrings>

    <add name="ADONETEntityTransactionTestEntities" connectionString="metadata=res://*/MyEntityModel.csdl|res://*/MyEntityModel.ssdl|res://*/MyEntityModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=sr-corp-ezpdev\sqlexpress;Initial Catalog=ADONETEntityTransactionTest;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

  </connectionStrings>

</configuration>

Lets create a new folder, DTO and add DTOs (Data Transfer Objects), aka, EntityClass for each of the tables, Category and Product.

Category Class:

 

public class Category

    {

        int categoryID;

        public int CategoryID

        {

            get { return categoryID; }

            set { categoryID = value; }

        }

       

        string categoryName;

        public string CategoryName

        {

            get { return categoryName; }

            set { categoryName = value; }

        }

    }

 

Product Class:

 

public class Product

    {

        int productID;

        public int ProductID

        {

            get { return productID; }

            set { productID = value; }

        }

       

        string productName;

        public string ProductName

        {

            get { return productName; }

            set { productName = value; }

        }

 

       

        string description;

        public string Description

        {

            get { return description; }

            set { description = value; }

        }

 

  string categoryID;

        public string CategoryID

        {

            get { return categoryID; }

            set { categoryID = value; }

        }

    }

Lets Add a BusinessObjects Folder and create our Business class. Am not looking at the conventions that will need to be followed. Idea is to get you aquainted with transactions in ADO.NET Entity Framework.

 

So our business class is very simple with one static method. This class is completely readable with necessary documentation wherever applicable.

public class BProductAndCategory

    {

        public static bool CreateCategoryAndProduct(Category categoryToAdd, Product productToAdd)

        {

            DbTransaction Transaction = null;

            using (EntityConnection DatabaseConnection = new EntityConnection("name=ADONETEntityTransactionTestEntities"))

            {

                try

                {

                    if (DatabaseConnection.State == ConnectionState.Closed)

                    {

                        DatabaseConnection.Open();

                    }

                    var CurrentContext = new ADONETEntityTransactionTestEntities(DatabaseConnection);

                    Transaction = CurrentContext.Connection.BeginTransaction();

 

                    #region Add the Category

                    CurrentContext.AddToCategory(categoryToAdd);

                    CurrentContext.SaveChanges();

                    #endregion

                    #region Get CategoryID of the newly added Category

                    int CategoryId = categoryToAdd.CategoryID; //return CategoryID of newly added Category.

                    if (CategoryId < 1)

                        throw new ApplicationException("Unable to obtain CategoryID of the newly added Category.");

                    #endregion

                    #region Insert Brand details

 

                    productToAdd.CategoryReference.EntityKey = new EntityKey("ADONETEntityTransactionTestEntities.Category", "CategoryID", CategoryId);

                    CurrentContext.AddToProduct(productToAdd);

                    CurrentContext.SaveChanges();

                    Transaction.Commit();

                    return true;

                    #endregion

                }

                catch

                {

                    Transaction.Rollback();

                    throw;

                }

                finally

                {

                    if (DatabaseConnection != null)

                    {

                        if (DatabaseConnection.State == ConnectionState.Open)

                        {

                            DatabaseConnection.Close();

                        }

                    }

                }

            }

        }

    }

At this stage, the solution should look something like the following screen shot:

 

 

Please bear with me. We are almost done and a very few steps away to accomplish our mission.

 

Now all the ingredietns are available and ready for us to finish our delicious DISH :)

 

All right, lets use the ingredients to prepare and consume the dish.

 

Lets go back to the Program.cs file and just add a few lines of code below: The code is completely readable with no extra documentation. So long as the code is readable I don’t prefer documentation.

class Program

    {

        static void Main(string[] args)

        {

            try

            {

                #region Populate Category

                Category ObjCategory = new Category();

                ObjCategory.CategoryName = "Clothing";

                #endregion

 

                #region Populate Product

                Product ObjProduct = new Product();

                ObjProduct.ProductName = "T-Shirt XL";

                ObjProduct.Description = "T-Shirt Extra Large";

                #endregion

 

                #region Add Category and Product

                if (BProductAndCategory.CreateCategoryAndProduct(ObjCategory, ObjProduct))

                    Console.WriteLine("Category and Product Added Successfully");

                

                #endregion

            }

            catch (Exception exp)

            {

                Console.WriteLine("Error Adding Product and Category. Error Message :: " + exp.Message);

            }

            finally

            {

                Console.ReadKey();

            }

        }

    }

Dish is on the table and ready for consumption.
 
Ok Lets consume it, Press F5 and VOILAAAA… I see a message on the screen, 'Category and Product Added Successfully.'

Verification


Go back to the databse.
 
Issue the following commands
 
Select * from Category
Select * from Product
 
VOILAAAA! I see the output. If you don't, let me know.
  

Conclusion

 
This is one of the approaches chosen to accomplish my mission. Should there be a sophisticated approach, please dot let me know. Also, correct me if I was incorrect or was travelling in a wrong direction.
 
Happy Programming!
 
Forget not to post your valueable feebback if you did like it! :)
 
I will meet you with another interesting and a rare post very soon!

 

Page copy protected against web site content infringement by Copyscape
About the Author

Deeraj

Full Name: Deeraj Chakravarthy
Member Level: Starter
Member Status: Member
Member Since: 10/29/2007 1:00:04 AM
Country: India

Qualification: BCA, MScIS, MDSE, PMI-ACP
Login to vote for this post.
Found interesting? Add this to:


Comments or Responses

Posted by: Nishithraj on: 9/16/2010 | Points: 10

Deeraj, Your way of explanation is good. But still I couldn't run this because I have only VS 2008. (I believe it supports only in VS 2010, Correct me If I'm wrong).

Atlast, I couldn't figure out the advantages using the entity framework. It would be better if you can share that too. Basically I'm an asp.net developer, whether it affects the page load performance If I'm implementing in any website. I'm asking these out of my curiosity.

I have given my 5 for the presentation and the unique subject.

Posted by: Pareenvatani on: 11/22/2010 | Points: 25

Hi deeraj

Thanks for information . Article looks nice.

I am stuck into thing . please help me out if its possible for you

- When a transaction begins for USER A , then the other user's should be on hold. And as soon as the USER A finishes the save operation the users can enter the block .
is this possbile?

Posted by: Akiii on: 4/16/2011 | Points: 25

Its showing DataBaseConnection namespace error. how to resolve it??

Thanks
Akiii

Posted by: Mcadeepuraj on: 5/4/2011 | Points: 25

nice articale and it works in my system.

Posted by: Bhupender.Yadav on: 4/12/2013 | Points: 25

can we make a login form using entity framework.

Login to post response

Comment using Facebook(Author doesn't get notification)