如果实体没有 ID,是否可以让 NHibernate 自动生成 ID,或者如果实体已经有 ID,则使用实体的 ID?

发布于 2024-09-27 13:27:42 字数 670 浏览 0 评论 0原文

根据 REST 理念,PUT 操作应该(摘自维基百科):

PUT http ://example.com/resources/142

更新集合中的地址成员,如果不存在,则创建它。

NHibernate 似乎有两种处理实体 ID 的方法:

  1. 自动生成 ID,无论用户设置什么值。
  2. 使用用户分配的ID,但失去所有自动生成功能。

PUT 操作的问题是关于创建实体(如果实体不存在)的部分。我的假设是,如果您 PUT 一个不存在的资源,它将使用 URL 指定的相同 ID 创建该资源(例如,如果我们使用上面的例子)。但是,NHibernate 不允许您设置自动生成的 ID。

所以我的问题是,如果实体没有 ID(或者具有 ID 类型的默认值,例如 0 表示整数),是否有一种方法可以让 NHibernate 自动生成 ID,但也可以使用以下命令保存实体用户设置的ID?

According to REST philosophy, a PUT operation should (taken from Wikipedia):

PUT http://example.com/resources/142

Update the address member of the collection, or if it doesn't exist, create it.

NHibernate seems to have two ways of dealing with entity IDs:

  1. Auto-generate an ID, regardless of what value the user set.
  2. Use the ID assigned by the user, but lose all auto-generation capabilities.

The problem here with a PUT operation is the part about creating the entity if it doesn't exist. My assumption is that if you PUT a resource that doesn't exist, it will create it with the same ID as specified by the URL (such as 142 if we use the above example). However, NHibernate doesn't allow you to set the ID if it's auto-generated.

So my question is, is there a way to get NHibernate to auto-generate an ID if the entity doesn't have one (or has the default value for the ID type, for example 0 for ints), but also save the entity with the ID that the user set?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凶凌 2024-10-04 13:27:42

Generally its a bad idea to use assigned ids.

The situation that you have is closer to the thing called NaturalId. You should use it I think. You will need to have two different properties, one for databases primary key, and second as a id that is visible to users.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文