Search code examples
c#nhibernatefluent-nhibernate

Trying to deal with nHibernate proxy classes due to inheritance


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


Solution

  • 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.