Showing posts with label NHibernate. Show all posts
Showing posts with label NHibernate. Show all posts

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)
{
}

Monday, December 08, 2008

This will save you some time

If you get error message "Association references unmapped class" from nhibernate check settings for Build Action for hbm.xml file. It should be "Embedded Resource".