1

I have a table-per-hierarchy setup (below are my domain objects). The problem is that when dealing with any of the returned nhibernate objects, they are proxy's of the base type.

I found this answer(as well as a few others), but this one also gave the link to this article for not losing lazy-loading.

PROBLEM

However, after attempting the articles suggestion of placing a generic method on the base class that returns the type of the type argument, I get a new error

error: "Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."

note: I understand that I can turn off lazy loading in the mappings, but as mentioned earlier, I was trying to take advantage of not losing lazy loading.

nHibernate Version: 3.3.1.4000 fluent nhibernate version: 1.3.0.733

public class ItemBase : IItemBase
{
    public virtual int Id { get; set; }
    public virtual int Version { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }

    public virtual T As<T>() where T : ItemBase
    {
        return this as T;
    }

    //removed for brevity 
}
public class Item : ItemBase
{
   public virtual Store Store { get; set; }
}

public class VendorItem : ItemBase
{
    public virtual Vendor Vendor { get; set; }
}

What am I missing that would resolve this issue?

UPDATE

To add to the problem, if I use the Nhibernate "Unproxy" method from the session:

NhSession.GetSessionImplementation().PersistenceContext.Unproxy

this only works if within the same session. However, in one case we are attempting to access outside the original session and I get an error: object was an uninitialized proxy

Community
  • 1
  • 1
pghtech
  • 3,642
  • 11
  • 48
  • 73

3 Answers3

2

The answer actually required using the Visitor pattern. NHibernate's return type is a proxy of the base class, so any attempts to cast to the desired type is not possible. The Visitor pattern allows you to identify the type of the object your after through polymorphism.

pghtech
  • 3,642
  • 11
  • 48
  • 73
0

Have you tried using the following?

NHibernateUtil.Initialize(myobject)
JP.
  • 5,536
  • 7
  • 58
  • 100
0

What's the .NET version? I remember that there are some problems with dynamic proxy of classes with generic parameters in .NET 3.5. By the way, when the associated session is no longer around, accessing unloaded property of proxies will case exception, so even when you sort the first problem out, the second problem with Unproxy() will still remains.

Doan Van Tuan
  • 525
  • 3
  • 11