如果实体没有 ID,是否可以让 NHibernate 自动生成 ID,或者如果实体已经有 ID,则使用实体的 ID?
根据 REST 理念,PUT
操作应该(摘自维基百科):
PUT http ://example.com/resources/142
更新集合中的地址成员,如果不存在,则创建它。
NHibernate 似乎有两种处理实体 ID 的方法:
- 自动生成 ID,无论用户设置什么值。
- 使用用户分配的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:
- Auto-generate an ID, regardless of what value the user set.
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,使用指定的 id 是一个坏主意。
您遇到的情况更接近于名为 NaturalId< /a>.我认为你应该使用它。您需要有两个不同的属性,一个用于数据库主键,第二个作为用户可见的 id。
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.