Wednesday, January 20, 2010

NHibernate: Is That Type a Proxy?

One of our applications does some reflection to map customizable content to domain objects. Anyone familiar with NHibernate and lazy loading has probably encountered proxy classes before. My problem: given a Type, I want the domain type.

It's easy to find out that proxy types extend the domain type they represent, so if I know that my Type is a proxy I can call BaseType to get the domain type. But how do I know if my Type is a proxy?

I tried numerous approaches, but the simplest I found was to look for a specific interface. Turns out proxies implement an interface called INHibernateProxy.

if (clazz.GetInterface(typeof(INHibernateProxy).FullName) != null)
clazz = clazz.BaseType;

Now clazz represents the domain type as desired.

There are other solutions of course, such as detecting the namespace (proxies have none), and possibly checking IsAutoClass (which I couldn't confirm in any documentation). This approach seems the most reliable.

Friday, January 8, 2010

NHibernate: Mapping a Generic List of Enum

I recently ran into a case where I wanted to have a collection of an enumeration on one of my domain classes.

E.g.

public class MyDomainClass
{
public List<MyRoleEnum> Roles { get; set; }
}

But how is do we map something like this in an xml mapping? A quick google didn't turn up the answer, so I played around a bit and found the following works as desired.

<bag name="Roles" table="MyDomainClass2Role">    
<key column="MyDomainClassId" />
<element column="Role" type="MyRoleEnum" />
</bag>

To confirm this usage I checked the documentation at hibernate.org. Turns out the <element /> tag was designed for value type bags anyway.