Search code examples
c#nhibernatenhibernate-mapping

NHibernate joined subclass causes error when retrieving list of base class


I have an Nhibernate mapping from my database to my c# code. I am going to lay out a simple representation of the structure.

class ItemHolder
{
    public virtual ICollection<Item> ItemCollection {get;set;}
}

class Item
{
    public virtual int Id{get;set;}
    public virtual string SomeValue{get;set;}
}    

And my NHibernate mappings

<class name="ItemHolder" table ="ItemHolders">
    ...
    <set name="ItemCollection" cascade="all-delete-orphan" inverse="true">
        <key column="ItemHolder"/>
        <one-to-many class="Item"/>
    </set>
</class>

<class name="Item" table="Items">
    <id name="ID" generator="native"/>
    ...
    <many-to-one name="ItemHolder" class="ItemHolder"/>
</class>

All this works fine and when I execute the following code I retrieve everything as expected.

bindingSource.DataSource = ISession.CreateQuery("select ih from ItemHolder as ih " +
            "left join fetch ih.ItemCollection")
            .SetResultTransformer(new DistinctRootEntityResultTransformer())
            .List<Item>();

As in I populate the binding source with ItemHolders each with a fully populated ItemCollection full of Items.

HOWEVER

when I add a joined sub class to Item for use elsewhere in my program like this:

class DerivedItem : Item
{
}

with the addition to the Item mapping of a joined subclass.

<class name="Item" table="Items">
    <id name="ID" generator="native"/>
    ...
    <many-to-one name="ItemHolder" class="ItemHolder"/>
    <joined-subclass name="DerivedItem" table="DerivedItems" extends="Item">
        <key column="ID"/>
    </joined-subclass>
</class>

Now things get funny. I can retrieve my derived items from the derived item table with no problem but when I try to execute the above c# code I get an error.

If I look at ((ItemHolder)bindingSource.Current).ItemCollection then my first item in the collection is mapped to class type Item however the second in the list is not mapped at all causing errors. I can see all its properties in the debugger but no type information.

I have isolated the error so that if I remove the joined-subclass from the Item mapping I have no problems, however I would like to have this capability.

I realise this is quite specific, and I have not given the exact code which may make things difficult to understand but maybe someone has experienced something similar or can spot a mistake in my mappings.


Solution

  • I found out that DerivedItem was also in the Item table, so the Item was being mapped to a derived item causing problems when adding to binding sources, as they were of different types.