How do I get NHibernate to save an entity if I assign it an ID, but generate one otherwise?

半城伤御伤魂 提交于 2019-12-23 23:09:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!