NHibernate ObjectProxy 使用延迟加载进行转换
我定义:
[ActiveRecord("BaseEntity", Lazy = true )]
class BaseClass {}
[ActiveRecord("DerivedEntity", Lazy = true )]
class DerivedClass : BaseClass {}
在数据库中 BaseEntity 和 DerivedEntity 是 1=1
我创建:
BaseClass myClass = New DerivedClass();
问题:
当我尝试询问时
myClass is DerivedClass
,我得到“假”,因为myClass 不是 DerivedClass,而是 BaseClassProxy。
如果没有延迟加载,NHibernate 不会创建代理对象,我也没有这个问题。
当我尝试将 myClass 转换为 DerivedClass 时,我收到此错误(显然),因为我尝试将 BaseClassProxy 对象转换为 DerivedClass。
Unable to cast object of type 'Castle.Proxies.BaseClassProxy' to type 'DerivedClass'.
问题:
如何获取实际分配的对象类型以与 DerivedClass 进行比较?
是否可以通过转换 BaseClassProxy 对象来获取 DerivedClass 的实例?
谢谢您的回复。
I defines:
[ActiveRecord("BaseEntity", Lazy = true )]
class BaseClass {}
[ActiveRecord("DerivedEntity", Lazy = true )]
class DerivedClass : BaseClass {}
In DB BaseEntity and DerivedEntity are 1=1
I create:
BaseClass myClass = New DerivedClass();
The problem:
When i try to ask
myClass is DerivedClass
i get "false" because myClass is not a DerivedClass instead is a BaseClassProxy.
Without Lazy Loading, NHibernate don't create a proxy object and i don't have this problem.
When i try to cast myClass to DerivedClass i get this error (obviously) because i try to cast a BaseClassProxy object to an DerivedClass.
Unable to cast object of type 'Castle.Proxies.BaseClassProxy' to type 'DerivedClass'.
The questions:
How can i obtain the real assigned object type to compare it with DerivedClass?.
Is it possible to cast BaseClassProxy object to obtain an instance of DerivedClass?.
Thank you for the replies.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,不可能将 NHibernate 代理
BaseClassProxy
转换为DerivedClass
的实例,因为BaseClassProxy
将继承自BaseClass
因此对您的DerivedClass
一无所知。为了能够使用它们的类型,您需要做的是将对象取消代理为它们的实际类型,即执行类似以下操作:其中 Session 是您的 NHibernate 会话。
Unfortunatly it's not possible to cast a NHibernate proxy
BaseClassProxy
to an instance ofDerivedClass
as theBaseClassProxy
will inherit fromBaseClass
and as such know nothing of yourDerivedClass
. What you need to do instead to be able to use their types is unproxy the objects to their actual types, i.e. do something like:Where Session is your NHibernate session.