Ошибка transaction not connected or was disconnected

In our develop environment all the ASP.NET application works just fine. However, when I deploy the site on the test machine, on some pages I get this exception:

NHibernate.TransactionException: Transaction not connected, or was disconnected
   at NHibernate.Transaction.AdoTransaction.CheckNotZombied() in d:CSharpNHNHnhibernatesrcNHibernateTransactionAdoTransaction.cs:line 406
   at NHibernate.Transaction.AdoTransaction.Rollback() in d:CSharpNHNHnhibernatesrcNHibernateTransactionAdoTransaction.cs:line 240

I have no idea on how to solve this issue. The only difference are the DB versions:
Develop: 10.0.5500 (2008 R2, SP1, Express)
Test: 10.0.5500 (2008, SP3)

Does someone has an idea what is going on here?

Перейти к контенту

I am getting

«Transaction not connected, or was disconnected error»

error when the transaction is either committed/rolled back after doing a bulk insert (along with some other operations).

using(var tran = Session.Session().BeginTransaction(IsolationLevel.Serializable))
    {
       // do something
       fullSession.Session().CreateSQLQuery(query).ExecuteUpdate();// this query bulk insert in a temp db
       // do something else
       tran.Commit()/ tran.RollBack();// if transaction is active and not already rolled back/committed
    }

If the query to bulk insert from a file into a temp database fails, I get this error on tran.Commit/rollback.

m.edmondson's user avatar

m.edmondson

30k27 gold badges120 silver badges204 bronze badges

asked May 31, 2012 at 18:43

Gyanendra Singh's user avatar

Gyanendra SinghGyanendra Singh

7752 gold badges11 silver badges26 bronze badges

2

Bulk Insert is a combination of Insert statements so if it fails it doesn’t roll back the transaction so if you really want to catch the error try using Try and catch block inside BEGIN and END transaction

answered May 31, 2012 at 18:54

praveen's user avatar

5

I was getting this exact same error using NHybernate while persisting an entity that had a property of type System.Data.SqlTypes.SqlDateTime? (Nullable).

Changing the property to a regular System.DateTime? fixed the problem.

answered Dec 27, 2012 at 8:47

Louis Somers's user avatar

Louis SomersLouis Somers

2,4203 gold badges25 silver badges55 bronze badges

2

I had some problem, but it gone after I close connection in MS SQL Managment studio.

answered Oct 22, 2016 at 21:51

xxarchexx's user avatar

xxarchexxxxarchexx

111 silver badge5 bronze badges

1

Транзакция не подключена или была отключена ошибка

я осознаю

«Транзакция не подключена или была отключена из-за ошибки»

ошибка, когда транзакция фиксируется/откатывается после выполнения массовой вставки (наряду с некоторыми другими операциями).

using(var tran = Session.Session().BeginTransaction(IsolationLevel.Serializable))
    {
       // do something
       fullSession.Session().CreateSQLQuery(query).ExecuteUpdate();// this query bulk insert in a temp db
       // do something else
       tran.Commit()/ tran.RollBack();// if transaction is active and not already rolled back/committed
    }

Если запрос на массовую вставку из файла во временную базу данных завершается неудачно, я получаю эту ошибку на tran.Commit/rollback.

Массовая вставка представляет собой комбинацию операторов Insert, поэтому в случае сбоя транзакция не откатывается, поэтому, если вы действительно хотите поймать ошибку, попробуйте использовать блок Try and catch внутри транзакции BEGIN и END.

ответ дан 31 мая ’12, 19:05

Я получал точно такую ​​же ошибку, используя NHybernate, сохраняя объект, который имел свойство типа System.Data.SqlTypes.SqlDateTime? (Обнуляемый).

Изменение свойства на обычное System.DateTime? исправлена ​​проблема.

ответ дан 27 дек ’12, 08:12

У меня была проблема, но она исчезла после того, как я закрыл соединение в студии MS SQL Managment.

ответ дан 22 окт ’16, 22:10

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

c#
sql-server
nhibernate
bulkinsert

or задайте свой вопрос.

The following is a representative snippet of my code where an unexpected, at least on my part, exception is being thrown at the transaction.Rollback() statement.

The exception is of type NHibernate.TransactionException and the message is «Transaction not connected, or was disconnected.» And the stack trace looks like this: NHibernate.Transaction.AdoTransaction.CheckNotZombied() at NHibernate.Transaction.AdoTransaction.Rollback().

IEmployeeService employeeService = new EmployeeService(session);
var people = ReadFromFile('c:temp.csv');

for (var person in people)
{
    ITransaction transaction = session.BeginTransaction();
    try
    {
        employeeService.Update(person);

        employeeService.CheckForRecursion();

        transaction.Commit();
    }
    catch(Exception exp)
    {
        if (!transaction.WasRolledBack)
            transaction.Rollback();
    }
}

The CheckForRecursion uses some SQL to look for any recursion introduced by the last update, if so I want to undo. When recursion has been introduced then an exception bubbles up from SQL, rightly so, and I catch it and attempt to rollback. That’s when I encounter the error.

I have wrapped the rollback in a try catch so the whole thing can carry on but I see the same exception on each subsequent iteration of the for loop.

Ideas? Is this pattern correct?

The following is a representative snippet of my code where an unexpected, at least on my part, exception is being thrown at the transaction.Rollback() statement.

The exception is of type NHibernate.TransactionException and the message is «Transaction not connected, or was disconnected.» And the stack trace looks like this: NHibernate.Transaction.AdoTransaction.CheckNotZombied() at NHibernate.Transaction.AdoTransaction.Rollback().

IEmployeeService employeeService = new EmployeeService(session);
var people = ReadFromFile('c:temp.csv');

for (var person in people)
{
    ITransaction transaction = session.BeginTransaction();
    try
    {
        employeeService.Update(person);

        employeeService.CheckForRecursion();

        transaction.Commit();
    }
    catch(Exception exp)
    {
        if (!transaction.WasRolledBack)
            transaction.Rollback();
    }
}

The CheckForRecursion uses some SQL to look for any recursion introduced by the last update, if so I want to undo. When recursion has been introduced then an exception bubbles up from SQL, rightly so, and I catch it and attempt to rollback. That’s when I encounter the error.

I have wrapped the rollback in a try catch so the whole thing can carry on but I see the same exception on each subsequent iteration of the for loop.

Ideas? Is this pattern correct?

The following is a representative snippet of my code where an unexpected, at least on my part, exception is being thrown at the transaction.Rollback() statement.

The exception is of type NHibernate.TransactionException and the message is «Transaction not connected, or was disconnected.» And the stack trace looks like this: NHibernate.Transaction.AdoTransaction.CheckNotZombied() at NHibernate.Transaction.AdoTransaction.Rollback().

IEmployeeService employeeService = new EmployeeService(session);
var people = ReadFromFile('c:temp.csv');

for (var person in people)
{
    ITransaction transaction = session.BeginTransaction();
    try
    {
        employeeService.Update(person);

        employeeService.CheckForRecursion();

        transaction.Commit();
    }
    catch(Exception exp)
    {
        if (!transaction.WasRolledBack)
            transaction.Rollback();
    }
}

The CheckForRecursion uses some SQL to look for any recursion introduced by the last update, if so I want to undo. When recursion has been introduced then an exception bubbles up from SQL, rightly so, and I catch it and attempt to rollback. That’s when I encounter the error.

I have wrapped the rollback in a try catch so the whole thing can carry on but I see the same exception on each subsequent iteration of the for loop.

Ideas? Is this pattern correct?

The following is a representative snippet of my code where an unexpected, at least on my part, exception is being thrown at the transaction.Rollback() statement.

The exception is of type NHibernate.TransactionException and the message is «Transaction not connected, or was disconnected.» And the stack trace looks like this: NHibernate.Transaction.AdoTransaction.CheckNotZombied() at NHibernate.Transaction.AdoTransaction.Rollback().

IEmployeeService employeeService = new EmployeeService(session);
var people = ReadFromFile('c:temp.csv');

for (var person in people)
{
    ITransaction transaction = session.BeginTransaction();
    try
    {
        employeeService.Update(person);

        employeeService.CheckForRecursion();

        transaction.Commit();
    }
    catch(Exception exp)
    {
        if (!transaction.WasRolledBack)
            transaction.Rollback();
    }
}

The CheckForRecursion uses some SQL to look for any recursion introduced by the last update, if so I want to undo. When recursion has been introduced then an exception bubbles up from SQL, rightly so, and I catch it and attempt to rollback. That’s when I encounter the error.

I have wrapped the rollback in a try catch so the whole thing can carry on but I see the same exception on each subsequent iteration of the for loop.

Ideas? Is this pattern correct?

Hey!

First this library is great. Thanks for all the time and effort.

I’m seeing a «Couldn’t rollback ADO.NET connection. Transaction not connected» from Quartz.Impl.AdoJobStore.JobStoreTX error preceded by «An error occurred while scanning for the next trigger to fire.» from Quartz.Core.ErrorLogger.

Usually they come in batches of two and three intermittently. This has only occurred after moving to a high availability sqlserver cluster.

From my googling it seems like the quartz library will retry after a set time. This is corroborated by the fact that my jobs are getting work their work done.

Ultimately I’d like to get them out of my error logs if possible.

I’m running non clustered using the following quartz configuration:

add key=»quartz.scheduler.instanceName» value=»RemoteEventAPIScheduler»
add key=»quartz.scheduler.instanceId» value=»AUTO»
add key=»quartz.threadPool.type» value=»Quartz.Simpl.SimpleThreadPool, Quartz»
add key=»quartz.threadPool.threadCount» value=»10″
add key=»quartz.threadPool.threadPriority» value=»Normal»
add key=»quartz.scheduler.exporter.type» value=»Quartz.Simpl.RemotingSchedulerExporter, Quartz»
add key=»quartz.scheduler.exporter.port» value=»555″
add key=»quartz.scheduler.exporter.bindName» value=»QuartzScheduler»
add key=»quartz.scheduler.exporter.channelType» value=»tcp»
add key=»quartz.scheduler.exporter.channelName» value=»httpQuartz»
add key=»quartz.scheduler.jobFactory.type» value=»Events_Jobs.Factories.FlowJobFactory, Events Jobs»
add key=»quartz.jobStore.misfireThreshold» value=»480000″
add key=»quartz.jobStore.type» value=»Quartz.Impl.AdoJobStore.JobStoreTX, Quartz»
add key=»quartz.jobStore.tablePrefix» value=»QRTZ_»
add key=»quartz.jobStore.driverDelegateType» value=»Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz»
add key=»quartz.jobStore.dataSource» value=»myDS»
add key=»quartz.dataSource.myDS.provider» value=»SqlServer-20″
add key=»quartz.jobStore.useProperties» value=»true»
add key=»quartz.jobStore.clustered» value=»false»

Any guidance would be super appreciated. Thanks again.

В нашей среде разработки все приложения ASP.NET работают нормально. Однако, когда я развертываю сайт на тестовой машине, на некоторых страницах возникает такое исключение:

NHibernate.TransactionException: Transaction not connected, or was disconnected
   at NHibernate.Transaction.AdoTransaction.CheckNotZombied() in d:CSharpNHNHnhibernatesrcNHibernateTransactionAdoTransaction.cs:line 406
   at NHibernate.Transaction.AdoTransaction.Rollback() in d:CSharpNHNHnhibernatesrcNHibernateTransactionAdoTransaction.cs:line 240

Понятия не имею, как решить эту проблему. Разница только в версиях БД: Develop: 10.0.5500 (2008 R2, SP1, Express) Test: 10.0.5500 (2008, SP3)

Кто-нибудь знает, что здесь происходит?

3 ответа

Лучший ответ

Возникла проблема с реализацией шаблона сеанса на запрос. ASP.NET является многопоточным, и сеанс закрывается при завершении потока, а не при завершении запроса. Существует множество примеров того, как управлять сеансом по запросу. и NHibernate имеет встроенный NHibernate.Context.WebSessionContext, но я предпочитаю используйте структуру внедрения зависимостей, такую ​​как Ninject.


6

Jamie Ide
8 Апр 2013 в 16:43

Это был комментарий, но у меня тоже была такая же проблема.

Эта ошибка может возникать, когда триггер вызывает исключение на уровне базы данных. Это вызовет откат транзакции, следовательно, исключение.


32

Daniel Little
14 Мар 2014 в 03:34

Другой проблемой может быть безопасность пользователя (опять же исключение уровня базы данных). В моем случае основная проблема с БД была:

The server principal "AppUser" is not able to access the database "AppDB" under the current security context.


0

Alex M
24 Мар 2016 в 20:13

В нашей среде разработки все приложения ASP.NET работают отлично. Однако, когда я развертываю сайт на тестовой машине, на некоторых страницах я получаю это исключение:

NHibernate.TransactionException: Transaction not connected, or was disconnected
   at NHibernate.Transaction.AdoTransaction.CheckNotZombied() in d:CSharpNHNHnhibernatesrcNHibernateTransactionAdoTransaction.cs:line 406
   at NHibernate.Transaction.AdoTransaction.Rollback() in d:CSharpNHNHnhibernatesrcNHibernateTransactionAdoTransaction.cs:line 240

Я не знаю, как решить эту проблему. Единственная разница в версиях БД:
Разработка: 10.0.5500 (2008 R2, SP1, Express)
Тест: 10.0.5500 (2008, SP3)

Есть ли у кого-то идея, что здесь происходит?

Ответ 1

Проблема с вашей реализацией шаблона сеанса за запрос. ASP.NET многопоточен, и сеанс закрывается, когда поток завершается, а не когда заканчивается запрос. Есть много примеры о том, как управлять сеансом за запрос, и NHibernate имеет встроенный NHibernate.Context.WebSessionContext, но я предпочитаю использовать инфраструктуру внедрения зависимостей, например Ninject.

Ответ 2

Это был комментарий, но у меня была такая же проблема.

Эта ошибка может возникать, когда триггер вызывает исключение уровня базы данных. Это приведет к откату транзакции и исключению.

Ответ 3

Еще одной проблемой может быть безопасность пользователя (опять-таки исключение уровня базы данных).
В моем случае основная проблема БД была:

The server principal "AppUser" is not able to access the database "AppDB" under the current security context.

In our develop environment all the ASP.NET application works just fine. However, when I deploy the site on the test machine, on some pages I get this exception:

NHibernate.TransactionException: Transaction not connected, or was disconnected
   at NHibernate.Transaction.AdoTransaction.CheckNotZombied() in d:CSharpNHNHnhibernatesrcNHibernateTransactionAdoTransaction.cs:line 406
   at NHibernate.Transaction.AdoTransaction.Rollback() in d:CSharpNHNHnhibernatesrcNHibernateTransactionAdoTransaction.cs:line 240

I have no idea on how to solve this issue. The only difference are the DB versions:
Develop: 10.0.5500 (2008 R2, SP1, Express)
Test: 10.0.5500 (2008, SP3)

Does someone has an idea what is going on here?

I am getting

«Transaction not connected, or was disconnected error»

error when the transaction is either committed/rolled back after doing a bulk insert (along with some other operations).

using(var tran = Session.Session().BeginTransaction(IsolationLevel.Serializable))
    {
       // do something
       fullSession.Session().CreateSQLQuery(query).ExecuteUpdate();// this query bulk insert in a temp db
       // do something else
       tran.Commit()/ tran.RollBack();// if transaction is active and not already rolled back/committed
    }

If the query to bulk insert from a file into a temp database fails, I get this error on tran.Commit/rollback.

m.edmondson's user avatar

m.edmondson

30.2k27 gold badges121 silver badges206 bronze badges

asked May 31, 2012 at 18:43

Gyanendra Singh's user avatar

Gyanendra SinghGyanendra Singh

8452 gold badges13 silver badges30 bronze badges

2

Bulk Insert is a combination of Insert statements so if it fails it doesn’t roll back the transaction so if you really want to catch the error try using Try and catch block inside BEGIN and END transaction

answered May 31, 2012 at 18:54

praveen's user avatar

5

I was getting this exact same error using NHybernate while persisting an entity that had a property of type System.Data.SqlTypes.SqlDateTime? (Nullable).

Changing the property to a regular System.DateTime? fixed the problem.

answered Dec 27, 2012 at 8:47

Louis Somers's user avatar

Louis SomersLouis Somers

2,5203 gold badges26 silver badges57 bronze badges

2

I had some problem, but it gone after I close connection in MS SQL Managment studio.

answered Oct 22, 2016 at 21:51

xxarchexx's user avatar

xxarchexxxxarchexx

111 silver badge5 bronze badges

1

Solution 1

There’s a problem with your session-per-request pattern implementation. ASP.NET is multi-threaded and the session is being closed when a thread terminates instead of when the request ends. There are many examples of how to manage session-per-request and NHibernate has a built in NHibernate.Context.WebSessionContext but I prefer to use a dependency injection framework such as Ninject.

Solution 2

This was a comment, but I had the same issue as well.

This error can occur when a trigger causes a database level exception. This will cause the transaction to be rolled back hence the exception.

Related videos on Youtube

How to use NHibernate in Visual Studio Projects

15 : 03

How to use NHibernate in Visual Studio Projects

Fix Windows 10 could not automatically detect this network's proxy settings Error

00 : 55

Fix Windows 10 could not automatically detect this network’s proxy settings Error

Fix minecraft io.netty.channel.abstractchannel$annotatedconnectexception connection refused

02 : 03

Fix minecraft io.netty.channel.abstractchannel$annotatedconnectexception connection refused

How to fix error ECONNREFUSED nodejs connect to mysql - Sửa lỗi ECONNREFUSED node js kết nối mysql.

05 : 32

How to fix error ECONNREFUSED nodejs connect to mysql — Sửa lỗi ECONNREFUSED node js kết nối mysql.

How to Fix "The DNS Server Isn't Responding" Error in Windows 10

07 : 42

How to Fix «The DNS Server Isn’t Responding» Error in Windows 10

The Complete Guide to Everything

Fix  Printer Not Accepting Print Command

03 : 03

Fix Printer Not Accepting Print Command

Fix connection reset error in minecraft 1.18.1 | internal exception java.net.socketexception 2022

03 : 33

Fix connection reset error in minecraft 1.18.1 | internal exception java.net.socketexception 2022

How to solve Citrix problem using Windows 10 latest version | Troubleshoot Citrix common issues

07 : 25

How to solve Citrix problem using Windows 10 latest version | Troubleshoot Citrix common issues

SSL error when connecting to Horizon connection server

05 : 52

SSL error when connecting to Horizon connection server

Unable to acquire JDBC Connection; nested exception is org.hibernate.exception tes cpns dan p3k

09 : 50

Unable to acquire JDBC Connection; nested exception is org.hibernate.exception tes cpns dan p3k

Hibernate javax.persistence.RollbackException Error while committing the transaction - MySQL

01 : 41

Hibernate javax.persistence.RollbackException Error while committing the transaction — MySQL

Getting org.hibernate.TransactionException nested transactions not supported error when deleting -

01 : 54

Getting org.hibernate.TransactionException nested transactions not supported error when deleting —

NHibernate mysql connection not closed - MySQL

01 : 17

NHibernate mysql connection not closed — MySQL

Comments

  • In our develop environment all the ASP.NET application works just fine. However, when I deploy the site on the test machine, on some pages I get this exception:

    NHibernate.TransactionException: Transaction not connected, or was disconnected
       at NHibernate.Transaction.AdoTransaction.CheckNotZombied() in d:CSharpNHNHnhibernatesrcNHibernateTransactionAdoTransaction.cs:line 406
       at NHibernate.Transaction.AdoTransaction.Rollback() in d:CSharpNHNHnhibernatesrcNHibernateTransactionAdoTransaction.cs:line 240
    

    I have no idea on how to solve this issue. The only difference are the DB versions:
    Develop: 10.0.5500 (2008 R2, SP1, Express)
    Test: 10.0.5500 (2008, SP3)

    Does someone has an idea what is going on here?

  • Thanks for your reply, but I (finally) figured it out. There was a trigger which causes an exception, which in turn caused a rollback.

  • True, in my case, I was inserting a string that was longer than what the database field accepted. The error message is not very useful.

  • Yep. I had some data type mismatch in the inserted data, and I got this incomprehensible error from NHibernate. Would have been nice if they could have just passed through the error from Sql instead of this confusing nonsense.

  • you can use the SQL Profiler to get the underlying script/command that caused the error. am a bit surprised the error doesnt bubble up correctly

  • In my case it was caused by a very slow sql query (took 34s to execute), so I added an index to make the sql query fast, and that fixed the issue. Not sure why the proper exception didn’t bubble up (e.g. «timeout», etc).

Recents

Related

  • Ошибка trans failsafe prog bmw e39
  • Ошибка tpws тойота прадо 150 бензин
  • Ошибка tpws тойота camry
  • Ошибка tpms хонда риджлайн
  • Ошибка tpms хендай туссан