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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With