I have run into this problem when using single table inheritance and a
table column as discriminator. At first I thought it was strange but
then thinking about it further I realized that when lazy loading NH
does not touch the database before creating the proxy object. Now how
should NH know if it should create a ProfileA-proxy or a ProfileB-
proxy without checking the database for the discrimiator value?
The answer is it cannot so it creates a proxy for the base class and
you get a Profile-proxy which of course is not castable to the derived
classes ProfileA or ProfileB.
Think of it this way. By telling NH to lazy-load you are telling it
not to look in the database but create a proxy instead and look in the
database later on. If the information that determines what proxy-type
it should create is in the database how could it possibly create an
proxy object of the correct type? And once the proxy object is created
as a base-class how could it possibly make it change into an derived
type when it accesses the database? It could of course look in the
database to determine the type of proxy to create but that would
defeat the whole purpose of lazy-loading.
This is what I think causes these types of problems but I can be wrong
because I have not confirmed it. I solved my problem by disabling lazy-
loading. I am also thinking about rewriting the code to use
composition instead of inheritance which I think would be a better
solution but currently I find inheritance to be easier to understand.
I think something like the player-role pattern could be used but I
still haven't reached a good understanding of how to use that pattern
and map it with NH....
/Jonas