当ID <1时,NHibernate写入值= NULL 0 [英] NHibernate write value = NULL when ID &lt; 0

查看:136
本文介绍了当ID <1时,NHibernate写入值= NULL 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们想要实现一个简单的规则,当实体的ID等于-1时,NHibernate将为数据库分配(保留)NULL。例如,我们有一个在系统帐户,应该被持久化到数据库作为NULL。

如果我们试图坚持到数据库的ID为-1得到一个外键异常,因为这个ID在外表中不存在。


$ b 我们使用NHibernate和FluentNhibernate。

解决方案

我想你没有一个适当的映射你的实体。如果它是正确的,你应该做出一些诀窍:你不应该看到一个ID,而是一个对另一个实体的引用,在这种情况下,你将会持有一个空值的引用。即使在错误的情况下,如果这个ID是可以为空的,你想映射实体的引用表示为一个ID(这几乎总是错误的),映射为可为空,所以你有int?您可以将null设置为null,而不是-1的技巧。



查看注释

如果自定义实体在内部用作空值,则会话拦截器可以帮助:在OnSave上工作,并通过用空值替换虚拟实体来处理特殊情况。
在这里你可以找到有关NH拦截器的文档
在11.2的同一个文档中,有与事件相关的部分,等同于这类问题。

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.

解决方案

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.

这篇关于当ID <1时,NHibernate写入值= NULL 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆