我如何让NHibernate保存一个实体,如果我分配一个ID,但生成一个否则? [英] How do I get NHibernate to save an entity if I assign it an ID, but generate one otherwise?
问题描述
PUT
请求应该更新资源,如果它不存在,就创建它。换句话说,如果我使用下面的URL: PUT http:// server / item / 5
如果一个ID为5的 Item
存在,被更新。如果 Item
不存在,且ID为5,则会创建一个新的 Item
,其ID为5 。
然而,我正在使用NHibernate进行持久化,并将我的ID映射为 Identity
。这意味着无论我给这个ID分配了什么值,当我保存一个新的 Item
时,NHibernate会自行替换它。
如何让NHibernate使用我分配的ID保存 Item
,而不改变ID映射为 Assigned $如果你使用Identity,DB将不会允许你输入一个值。
也就是说,如果你的数据库有一些特殊的语法来允许在标识字段中插入显式值,你可以实现你自己的生成器,我保证它会容易出错,很难调试,并不是很有用。但这是可能的。
学习所有内容 https://nhibernate.svn.sourceforge.net/svnroot/nhibernate/trunk/nhibernate/src/NHibernate/Id 并开始创建您的Frankenstein: - )
According to the REST philosophy, a PUT
request should update the resource at a URL if it exists, and create it if it doesn't exist. So in other words, if I use the following URL:
PUT http://server/item/5
If an Item
exists with an ID of 5, it will be updated. If an Item
doesn't exist with an ID of 5, a new Item
will be created with an ID of 5.
However, I'm using NHibernate for persistence, and I mapped my IDs as Identity
. This means that no matter what value I assign the ID, NHibernate will replace it with its own when I save a new Item
.
How do I get NHibernate to save an Item
with the ID that I assign it, without changing the ID mapping to Assigned
?
If you use Identity, the DB won't allow you to enter a value.
That said, if your DB has some special syntax to allow inserting with explicit values in Identity fields, you can implement your own generator, which I guarantee will be error prone, hard to debug, and not very useful. But it's possible.
Study everything in https://nhibernate.svn.sourceforge.net/svnroot/nhibernate/trunk/nhibernate/src/NHibernate/Id and start creating your Frankenstein :-)
这篇关于我如何让NHibernate保存一个实体,如果我分配一个ID,但生成一个否则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!