NHibernate write value = NULL when ID < 0

烈酒焚心 提交于 2019-12-11 07:07:42

问题


We would like to implement a simple rule in which NHibernate would assign (persist) NULL to the database when the ID for the entity is equal to -1. For example, we have an "in system" account which should be persisted to the database as NULL.

If we try to persist the ID of -1 to the database we get a Foreign key exception because the ID does not exist in the foreign table.

We are using NHibernate with FluentNhibernate.


回答1:


I think you didn't a proper mapping of your entity. If it were correct, you should made any trick: you should not see an ID, but a reference to another entity, and in this case you will persist the reference with a null value. Even in the wrong case you want map the entity with a reference expressed as an ID ( that is almost always wrong ) if this id is nullable, map it as a nullable so you have int? and you can fit null to mean null, instead of the -1 trick.

See Comments

If a custom entity is internally used as a null value, a session interceptor could help: working on the OnSave and treat the special case by replacing the dummy entity with null. Here you can find the documentation about NH interceptors. At the 11.2 chaper od the same doc there is the portion related to events, equivalents for this kind of problem.



来源:https://stackoverflow.com/questions/5132400/nhibernate-write-value-null-when-id-0

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