Thursday, March 6, 2008

How to use transaction in LINQ using C#

I looked in to the LINQ and found very interesting. LINQ generates DataContext class which provides classes and methods which is used in OR-Mapping. You can also use your own stored procedures and views with LINQ. You may require using transaction with your own Stored Procedures for Insert, Delete or updating operations.

System.Data.Common.DbTransaction class provides the Transaction object.

Lets start with new project, you can select new project from Start -> All Programs -> Microsoft Visual Studio 2008and click on Microsoft Visual Studio 2008. Create new Asp.net website. Right click on website from solution explorer and select LINQ to SQL classes from Add New Item.

This will generate dbml file in App_Code folder. Select the tables, views, stored procedures and function from server explorer and drag it on dbml file. DataContext class generates methods for each SPs, functions and views.


 

System.Data.Common.DbTransaction trans = null;

DataClassesDataContext objDataClass = new
DataClassesDataContext();

try
{


// Open the connection
objDataClass.Connection.Open();

// Begin the transaction
trans = objDataClass.Connection.BeginTransaction();

// Assign transaction to context class
// All the database operation perform by this object
//will now use transaction

objDataClass.Transaction = trans;

//Perform the Operations

///Insert

//Update

//Delete

}

catch (Exception ex)
{

// Rollback transaction
if (trans != null)
trans.Rollback();

}
finally
{

// Close the connection

if (objDataClass.Connection.State == ConnectionState.Open)

objDataClass.Connection.Close();

}


 

Fig - Code for Transaction in LINQ using C#

No comments: