3

Using fluent NHibernate I have a property on a class mapped using Version

Version(x => x.Version);

When I save the object, the Version property gets incremented in the database as I would expect, but the value of the property on the object only seems to change sometimes.

using (var tx = session.BeginTransaction())
{
    session.Merge(item);
    tx.Commit();

    item.Version;  // Sometimes this is still 1, when I expect it to be 2.
}

The problem is then that if it remains as 1 and I make more changes and save again I get a StaleObjectStateException.

What's weird is that sometimes it works fine and the item.Version value does get correctly incremented, but I can't figure out the difference between the cases where it does and the cases where it doesn't.

I've tried searching but can't seem to find any documentation on this. Can anyone explain what NHibernates expected behaviour is with the Version mapping?

[NHibernate version 2.1.2]

4

3 回答 3

2

ISession.Merge文档中:

将给定对象的状态复制到具有相同标识符的持久对象上。如果当前没有与会话关联的持久实例,它将被加载。返回持久实例。如果给定实例未保存,则保存副本并将其作为新的持久实例返回。给定的实例不会与会话关联。

所以,它不会修改item.

(我可能会补充一点,我从未Merge在我的应用程序中使用过。您可能想查看如何处理附加和分离实体)

于 2011-06-10T14:50:51.093 回答
1

你试过了吗

item = session.Merge(item);
tx.Commit();

?

于 2011-06-10T15:13:03.947 回答
0

您需要在更新的版本传播到您的实体之前刷新会话。除非您刷新会话,否则您有责任自行使实体保持最新状态。

您通常应该让会话在关闭时自行刷新。但是,在某些情况下,您依赖于通过 nhibernate 发生的数据库更新,而不是您对实体本身所做的设置,您可能需要在提交后自己刷新会话。在这种情况下,请注意,当您刷新会话时,任何脏的实体都将被提交。这可能是不可取的,因此请确保范围非常有限。

于 2011-06-10T14:17:54.820 回答