Search code examples
nhibernateproxy-classes

After calling NHibernate.Initialize(proxyObject) I'm getting wrong objectType


I have object hierarchy Parent->Child (Lazy loading is set to true by default) Now I'm loading all Parent objects from database. All child object will have the type ChildProxyGUID.

then I write the

IList<Parent> parentList = NHibernateHelper.List<Parent>();
foreach(Parent parent in parentList)
{
  if(!NHibernateUtil.IsInitialized(parent.Child))
  {
    NHibernateUtil.Initialize(parent.Child);
    if(parent.Child.GetType() != typeof(Child)) //parent.Child.GetType() return me proxy type
      throw new ArgumentException("wrong type");
  }
}

How can I convert parent.Child to Real type "Child". I need the real type (Child) because of system checking. This example is simple in real life I have a very complicated mappings and relations.

Any ideas there?


Solution

  • Try with:

    var realObject = session.GetSessionImplementation()
                            .PersistenceContext.Unproxy(parent.Child)
    

    However, it's a bad a idea to have your code rely on this type of checks, as it violates the LSP, creating code that is harder to maintain.