NHibernate更新列=列 - 1

时间:2012-10-01 18:47:07

标签: nhibernate

我无法在nhibernate的上下文中执行以下更新。

using(ITransaction transaction = session.BeginTransaction())
{
    // FIRST I'm GETTING A LIST OF ITEMS IN A MANNER LIKE THIS
    var itemsToDelete = session.QueryOver<Item>()
                                   .Where(i => i.ReferenceObject.Id == otherIdValue)
                                   .List<Item>();

    // THEN I"M LOOPING THROUGH THEM
    for(itemToDelete in itemsToDelete)
    {

        session.Delete(itemToDelete);

        using (iDB2Command command = (iDB2Command)_session.Connection.CreateCommand())
        {
            command.CommandText = "update TABLE_NAME set sequence = (sequence - 1) where id = @someId and sequence > @sequenceNumberDeleted";
            command.DeriveParameters();
            command.Parameters["@someId"].Value = idValue;
            command.Parameters["@sequenceNumberDeleted"].Value = itemToDelete.Sequence;
        }
    }

    transaction.commit()
}

问题似乎与sequ​​ence =(sequence - 1)有关。每次调用例程时,NHibernate都会抛出“意外的行数”异常。虽然研究我发现的与此异常相关的大多数文章都是由更新其他行的表上的触发器引起的。在这种情况下,表上没有任何触发器。另外,如果我替换sequence = 5或其他一些常量,则update语句执行时没有任何问题。

DATE TIME [10] ERROR App.Controllers.AController - Unexpected row count: 2; expected: 1
DATE TIME [10] ERROR App.Controllers.AController -    at NHibernate.AdoNet.Expectations.BasicExpectation.VerifyOutcomeNonBatched(Int32 rowCount, IDbCommand statement)
   at NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation)
   at NHibernate.Persister.Entity.AbstractEntityPersister.Delete(Object id, Object version, Int32 j, Object obj, SqlCommandInfo sql, ISessionImplementor session, Object[] loadedState)
   at NHibernate.Persister.Entity.AbstractEntityPersister.Delete(Object id, Object version, Object obj, ISessionImplementor session)
   at NHibernate.Action.EntityDeleteAction.Execute()
   at NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
   at NHibernate.Engine.ActionQueue.ExecuteActions(IList list)
   at NHibernate.Engine.ActionQueue.ExecuteActions()
   at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
   at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event)
   at NHibernate.Impl.SessionImpl.Flush()
   at NHibernate.Transaction.AdoTransaction.Commit()
   at App.Controllers.AController.AMethod(Int32[] otherIdValues, Int32 someIdValue, String someReferenceValue) in    <path>\App\Controllers\AController.cs:line 117

有人可以帮助我指出正确的方向吗?

编辑: 迭戈是对的。这是我急于求成的。 对此代码的实际调用是在事务内部,然后我在事务上调用commit。

1 个答案:

答案 0 :(得分:0)

此后我找到了问题的原因。实际的陈述并没有按照我的想法顺序生成。相反,update命令在delete命令之前执行,因此delete命令抛出了意外的行计数异常,而不是我之前想到的更新命令。