Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate ObjectProxy casting with Lazy Loading

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.

like image 582
manuellt Avatar asked Dec 28 '22 11:12

manuellt


1 Answers

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.

like image 113
Johannes Kommer Avatar answered Jan 07 '23 22:01

Johannes Kommer