为什么NHibernate抛出"StaleObjectStateException"?

Kov*_*xey 6 c# nhibernate hibernate

我正在编写项目并使用NHibernate 3.1

SimpleTest的:

Forum forum = Session.CreateCriteria<Forum>().Add(Restrictions.Eq("UrlName", "reportabug")).UniqueResult<Forum>();
forum.TopicsCount++;
IForumRepository forumRepository = new ForumRepository(SessionFactory);
forumRepository.Update(forum);

public virtual void Update(TEntity entity)
{
    if (!session.Transaction.IsActive)
    {
        TResult result;
        using (var tx = session.BeginTransaction())
        {
            session.SaveOrUpdate(entity)
            tx.Commit();
        }
        return result;
    }
    session.SaveOrUpdate(entity)
}
Run Code Online (Sandbox Code Playgroud)

最后一次更新抛出异常:

StaleObjectStateException was unhandled by user code:
    Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
Run Code Online (Sandbox Code Playgroud)

SQL查询:

UPDATE Forums
SET    Name = 'Forums Issues (not product support)' /* @p0 */,
       UrlName = 'reportabug' /* @p1 */,
       Description = 'Use this forum to report issues with the online forums application. When reporting an issue please include relevant details such as repro steps, error messages and browser version.' /* @p2 */,
       CategoryId = 'b2cc232c-0d5c-4f35-bb6f-29c67d7d40c2' /* @p3 */,
       TopicsCount = 1 /* @p4 */
WHERE  ForumId = '864046b7-ca57-48c4-8a81-082103223527' /* @p5 */
Run Code Online (Sandbox Code Playgroud)

ForumId是对的.也许这是并发?有什么想法吗?

Man*_*uPK 8

StaleObjectStateException是一种休眠方式,确保数据一致性在这里读取API .Hibernate维护version它更新的对象,如果DB和内存中版本不匹配,则会抛出错误.在此处阅读有关乐观锁定机制的更多信息.

因此,使用此信息调试应用程序.我不熟悉C#语法,但我认为第二次保存应该是else有条件的.