Could not synchronize database state with session-Nhibernate 和 Rebus 并发问题

Could not synchronize database state with session- Nhibernate and Rebus concurrency issue

在 Nhibernate 中使用 Rebus 时,在 table 中存储订户详细信息时出现类似

的错误
NHibernate.Event.Default.AbstractFlushingEventListener

NHibernate.AdoNet.TooManyRowsAffectedException: Unexpected row count: 5; expected: 1
   at NHibernate.AdoNet.Expectations.BasicExpectation.VerifyOutcomeNonBatched(Int32 rowCount, IDbCommand statement)
   at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session)
   at NHibernate.Persister.Entity.AbstractEntityPersister.UpdateOrInsert(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session)
   at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Int32[] dirtyFields, Boolean hasDirtyCollection, Object[] oldFields, Object oldVersion, Object obj, Object rowId, ISessionImplementor session)
   at NHibernate.Action.EntityUpdateAction.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)

这可能是由于所有订阅者并发而发生的,因为如果我使用调试器,那么随着时间的推移,它会出乎意料地工作。

在此代码中出现异常

  public void Insert(ISagaData sagaData, string[] sagaDataPropertyPathsToIndex)
        {
            try
            {
                var nSagaData = new NDbSagaData
                {
                    Id = sagaData.Id,
                    Revision = sagaData.Revision++,
                    Data = JsonConvert.SerializeObject(sagaData, Formatting.Indented, Settings)
                };
                PersistenceManager.Save(nSagaData);
            }
            catch (Exception ex)
            {
                _log.Error("Insert Exception " + ex.Message);
                System.IO.File.AppendAllText("C:\TestFolder\WriteText.txt", "Insert fromSource - " + ex.Message);
                throw new OptimisticLockingException(sagaData, ex);
            }
        }

它说,'意外的行数:3;预期:1'

会是什么原因?

看起来你已经实现了一个基于 NHibernate 的 saga 持久化器,而且它似乎检测到了一个竞争条件,我猜测这会导致回滚事务。

我想问题是为什么 出现了竞争条件。当 NHibernate 的乐观并发检查失败时会发生 "unexpected row count" 异常,但在那种情况下我会期待一条消息说 "unexpected row count 0; expected 1".

如果我是你,我会使用 Rebus 的内置 SQL Server saga 持久化器,因为看起来你无论如何都要将 saga 数据序列化到一个列中。