“New transaction is not allowed because there are other threads running in the session.” : Entity Framework

We often face this exception, “New transaction is not allowed because there are other threads running in the session.” when we try to try to save the object after adding to the context or after the edit action at “ObjectContext.SaveChanges()”.

First let us see, why this occurs. Consider the following snippet,

var entity = from e in context.Table_name

                      where e.id == id

                     select e;  //Selects the record from db with  id

foreach(var entityRecord in entity)

{

entityRecord.name =”some string”;

context.ObjectStateManager.ChangeObjectState(entity,EntityState.Modified);

context.SaveChanges(); //The exception arises here

}

The reason for this exception is, the “entity” object is of type Enummerable and it has to be converted into a list before it is iterated for edit/delete. Please find the change highlighted below:

var entity = from e in context.Table_name

                      where e.id == id

                     select e;  //Selects the record from db with  id

foreach(var entityRecord in entity.ToList)

{

entityRecord.name =”some string”;

context.ObjectStateManager.ChangeObjectState(entity,EntityState.Modified);

context.SaveChanges();

}

You can also do it, as soon as the LINQ ends. Hope it will solve the issue. Happy Coding!

Advertisements

One response to ““New transaction is not allowed because there are other threads running in the session.” : Entity Framework

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