Меню

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

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)

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

4b9b3361

Ответ 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.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка trans failsafe prog bmw e39
  • Ошибка traceback most recent call last file