问题
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
?
回答1:
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 :-)
来源:https://stackoverflow.com/questions/3886877/how-do-i-get-nhibernate-to-save-an-entity-if-i-assign-it-an-id-but-generate-one