NHibernate ObjectProxy 使用延迟加载进行转换

发布于 2024-12-13 01:11:02 字数 926 浏览 3 评论 0原文

我定义:

[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'.

问题:

  1. 如何获取实际分配的对象类型以与 DerivedClass 进行比较?

  2. 是否可以通过转换 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:

  1. How can i obtain the real assigned object type to compare it with DerivedClass?.

  2. Is it possible to cast BaseClassProxy object to obtain an instance of DerivedClass?.

Thank you for the replies.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荭秂 2024-12-20 01:11:02

不幸的是,不可能将 NHibernate 代理 BaseClassProxy 转换为 DerivedClass 的实例,因为 BaseClassProxy 将继承自 BaseClass因此对您的 DerivedClass 一无所知。为了能够使用它们的类型,您需要做的是将对象取消代理为它们的实际类型,即执行类似以下操作:

public T UnProxyObjectAs<T>(object obj)
{
    return Session.GetSessionImplementation().PersistenceContext.Unproxy(obj) as T;
}

var derived = UnProxyObjectAs<DerivedClass>(myClass);

其中 Session 是您的 NHibernate 会话。

Unfortunatly it's not possible to cast a NHibernate proxy BaseClassProxy to an instance of DerivedClass as the BaseClassProxy will inherit from BaseClass and as such know nothing of your DerivedClass. 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:

public T UnProxyObjectAs<T>(object obj)
{
    return Session.GetSessionImplementation().PersistenceContext.Unproxy(obj) as T;
}

var derived = UnProxyObjectAs<DerivedClass>(myClass);

Where Session is your NHibernate session.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文