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 On Mar 19, 6:02 pm, RoyWagner <[email protected]> wrote: > This is the situation: > > I have an abstract Profile class and 2 derived classes let’s call the > ProfileA and ProfileB. > Then mapping structure that I use is table per class hierarchy. > > I also have a user class that have reference to a Profile: > > Public class User > { > public virtual Profile Profile { get; set; } > > } > > I use lazy load for the Profile property. > > The problem is that when try to cast the User.Profile to one of the > derived classes(PofileA or ProfileB) I get an error that I can’t cast > ProfileProxy16982… to ProfileA. > NHibernate create ProfileProxy object in order to support the lazy > load and that prevent me from casting the Profile object. > > The only solution I have right now is to cancel the lazy load. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "nhusers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/nhusers?hl=en -~----------~----~----~----~------~----~------~--~---
