Nhibernate 中具有复合 ID 的意外代理对象 [英] Unexpected proxy objects in Nhibernate with composite ID's
问题描述
我有一个使用复合 ID 的数据结构(我不想更改为单个)除了多对一连接(如果连接为空,而不是将属性映射到 null,而是将其映射到空代理对象)之外,一切都可以正常加载.我写了一个丑陋的工作(见下面).有什么解决办法吗?
I have a data structure which uses composite ids (Which I dont wish to change to single) Everything loads fine except for many-to-one joins which if the join is empty, instead of mapping the property to null, maps it to an empty proxy object. I have written an ugly work around( see bleow). Any solutions to this?
私有节点_Parent;
private Node _Parent;
public Node Parent
{
get
{
return this._Parent;
}
set
{
this._Parent = Proxy.Check<Node>(value);
}
}
internal static class Proxy
{
public static T Check<T>(T obj) where T : PersistentObject
{
if (obj is NHibernate.Proxy.INHibernateProxy && obj != null)
{
try
{
int id = obj.ID;
return obj;
}
catch //Proxy only object cant retrieve ID
{
return null;
}
}
else
{
return obj;
}
}
}
以映射文件开头
<class name="Node" table="Node">
<composite-id>
<key-property name="ID"/>
<key-property name="VersionID"/>
</composite-id>
和访问者
<many-to-one name="Node" class="Node" >
<column name="NodeID"/>
<column name="VersionID" />
</many-to-one>
推荐答案
不确定这是否是这种情况的完美解决方案,但是当我在使用旧数据库工作时遇到同样的问题时,这为我解决了这个问题复合键.
Not exactly sure if this is the perfect fix for this situation, but this fixed the issue for me when I encountered the same problem while working on an old DB with composite keys.
通过将 not-found 设置为忽略链接,NHibernate 会将空对象视为空对象而不是异常.当使用这种技术时,NHibernate 将执行一个单独的查询,所以可能会有小的性能影响,因为这基本上是急切加载对象.
By setting not-found to ignore on your links, NHibernate will treat empty objects as null instead of exceptions. When using this technique NHibernate will execute a seperate query so there may be small performance hits, as this is basically eager loading the object.
您可以尝试直接加载对象而不是使用这种技术,但我感觉它会返回一个异常,因为它期待一个对象(非空).如果这不起作用,我建议在 NHibernate 论坛上发布一个问题,因为我绝对不是这方面的专家,但这对您来说可能是一个较小/不那么丑陋的工作.
You could try just eager loading the object instead of using this technique, but I have a feeling it would return an exception as it would be expecting an object (not null). I would suggest posting a question in the NHibernate forums if this doesn't work as I am definately not an expert in this area, but this may be a smaller/less ugly work around for you.
例如:
<many-to-one name="Node" class="Node" not-found="ignore">
<column name="NodeID"/>
<column name="VersionID" />
</many-to-one>
希望这会有所帮助,
杰
这篇关于Nhibernate 中具有复合 ID 的意外代理对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!