Transaction in Linq To Entity or Entity Framework


A transaction is a series of operations performed as a single unit of work. Entity Framework transactions are a part of its internal architecture. The SaveChanges method operates within a transaction and saves results of the work. It is designed to ensure data integrity.

Imagine we want the SaveChanges to be only a part of more complicated update process. For example, we want to execute several SaveChanges as one operation in the single ObjectContext.
The possible solution is to use the database connection. Here is a sample code:

STP_TAXEntities context = new STP_TAXEntities();

DbTransaction dbTran = null;

Message = string.Empty;

try

{

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

{

context.Connection.Close();

}

context.Connection.Open();

dbTran = context.Connection.BeginTransaction();

int Count = 0;

Count = context.COUNTRY_TAXQDI_ALLOWABILITY.Where(a => a.COUNTRY_CODE == CountryCode && a.CLIENT_TOKEN == ClientToken).Count();

if (Count > 0)

{

var query = from a in context.COUNTRY_TAXQDI_ALLOWABILITY

where a.COUNTRY_CODE == CountryCode &&   a.CLIENT_TOKEN == ClientToken

select a;

foreach (var item in query)

{

context.COUNTRY_TAXQDI_ALLOWABILITY.DeleteObject(item);

context.SaveChanges();

}

}

else

{

Message = “No security country exception found for selected country.”;

}

dbTran.Commit();

}

catch (Exception)

{

dbTran.Rollback();

throw;

}

finally

{

context.Connection.Close();

}

As we can easily ensure, the transaction is opened on database connection, and SaveChanges are added to this transaction.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: