Wednesday, March 11, 2009

Hibernate (NHibernate) and Polymorphism

If you use lazy loading on base class, NHibernate will create proxy class of base class so you will not be able to use is operator to check type of object. For example:


abstract class Base
{
};

class A : Base
{
}

class B: Base
{
}

class C
{
public virtual Base BaseClass {get; set;}
}


If you now list all C objects from database and try to check of what type is C.BaseClass with

if (c.BaseClass is A)
{
}
else if (c.BaseClass is B)
{
}
else
{
//ERROR
}


you will get an error.

Simplest way to solve this problem is to add method in base class that will returns instance to itself:


abstract class Base
{
public virtual Base This()
{
return this;
}
};


Now, you can check:

if (c.BaseClass.This() is A)
{
}
else if (c.BaseClass.This() is B)
{
}

3 comments:

Sumod said...

Your post saved me a bunch of time spent in a crunch situation :-) Thanks!

Diego Varese said...

This works!!! Thanks!

Asava Samuel said...

This is WAY easier to use than NHibernate:
https://www.kellermansoftware.com/p-47-net-data-access-layer.aspx