我正在尝试解决这个问题,但到目前为止我还没有找到任何合适的答案。
我正在用 C# 编写 SQLite DB 应用程序,在某些时候我使用 session.SaveOrUpdate(object)
将元素保存到 DB 或更新它
但是根据完成的操作(保存或更新),我需要做不同的事情,所以我的问题是,有没有办法知道使用 SaveOrUpdate 方法是否对象是第一次保存或者是否更新了吗?
提前致谢!
最佳答案
A SaveOrUpdate
方法是无效的,因此,我们必须在我们的代码中进行检查。见:
9.4.2. Updating detached objects
我们应该提供设置 unsaved-value
在映射中:
NHibernate distinguishes "new" (unsaved) instances from "existing" (saved or loaded in a previous session) instances by the value of their identifier (or version, or timestamp) property. The unsaved-value attribute of the (or
<version>
, or<timestamp>
) mapping specifies which values should be interpreted as representing a "new" instance.<id name="Id" type="Int64" column="uid" unsaved-value="0"> <generator class="hilo"/> </id>
因为否则:
If unsaved-value is not specified for a class, NHibernate will attempt to guess it by creating an instance of the class using the no-argument constructor and reading the property value from the instance.
下一步只是根据要传递给 SaveOrUpdate
的实例检查该设置
如果我们确实设置了 unsaved-value="0"
,我们可以检查甚至在 SaveOrUpdate()
之前会发生什么被称为:
entity.ID == default(int);
关于c# - 知道元素是否已保存或更新 Nhibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49644228/