c# - 知道元素是否已保存或更新 Nhibernate

标签 c# database sqlite nhibernate

我正在尝试解决这个问题,但到目前为止我还没有找到任何合适的答案。 我正在用 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/

相关文章:

c# - 如果没有 “return”,C# lambda 如何工作?

c# - 无法在 C# 中登录我的 netsuite 帐户

c# - “Could not find a part of the path” Azure WebApp 中的文件读取操作错误

ios - 本地 SQLite 数据库在多大程度上适合 iOS 应用程序?

c# - SQLite 使用用户输入选择查询 C#

ios - 只有 10 个 CustomViewCells 是正确的

c# - 如何从UserControl1 WPF MVVM中的按钮将数据从一个UserControl1传递到UserControl2

sql - 使用内存数据库从多个数据库查询

mysql - 计算mysql中两个时间戳的时间差

java - 如何读取并显示一开始默认设置的用户等级