NHibernate ObjectProxy Casting with Lazy Loading

I define:

[ActiveRecord("BaseEntity", Lazy = true )] class BaseClass {} [ActiveRecord("DerivedEntity", Lazy = true )] class DerivedClass : BaseClass {} 

In DB BaseEntity and DerivedEntity: 1 = 1

I'm creating:

 BaseClass myClass = New DerivedClass(); 

Problem:

When i try to ask

 myClass is DerivedClass 

I get "false" because myClass is not a DerivedClass, but a base class.

Without Lazy Loading, NHibernate does not create a proxy object, and I do not have this problem.

When I try to use myClass for DerivedClass, I get this error (obviously) because I'm trying to apply a BaseClassProxy object to DerivedClass.

 Unable to cast object of type 'Castle.Proxies.BaseClassProxy' to type 'DerivedClass'. 

Questions:

  • How can I get the real type of the assigned object to compare it with DerivedClass ?.

  • Can I use a BaseClassProxy object to get an instance of DerivedClass ?.

Thanks for answers.

+4
source share
1 answer

Unfortunately, it is not possible to make the NHibernate BaseClassProxy instance of DerivedClass , because BaseClassProxy inherits from BaseClass and as such does not know anything about your DerivedClass . Instead, you need to use your types in order not to use objects for their actual types, for example:

 public T UnProxyObjectAs<T>(object obj) { return Session.GetSessionImplementation().PersistenceContext.Unproxy(obj) as T; } var derived = UnProxyObjectAs<DerivedClass>(myClass); 

Where the session is an NHibernate session.

+10
source

Source: https://habr.com/ru/post/1379267/


All Articles