views:

20

answers:

1

I have an NHibernate object that is a superclass (let's call it "Super"), and a subclass that inherits from it (let's say it's called "Sub").

<class name="Super" table="SuperThings">
    <id name="Id" type="System.Int32" column="SuperId">
        <generator class="identity" />
    </id>

    <joined-subclass name="Sub" table="SubThings" extends="Super" lazy="true">
        <key column="SubId" />
    </joined-subclass>
</class>

I have a separate class (called "Widget") with a property of type Super.

<class name="Widget" table="Widgets" lazy="true">
    <id name="Id" type="System.Int32" column="NoteId">
      <generator class="identity" />
    </id>
    <many-to-one name="SuperProperty" column="SuperId" class="SuperClass" />
</class>

When I access SuperProperty on an instance of a Widget, NHibernate attempts to lazily load it, but I get this error:

More than one row with the given identifier was found: 1, for class: Super

There is only one record in SuperThings with an id of 1, and a separate record in SubThings associated to it. After using the NHibernate Profiler and debugging my code, it looks like NHibernate is trying to instantiate an object whose type is the subclass.

Why is it doing that? Is there something wrong with how I'm thinking this should be mapped?

Obviously, this is a simplified version of what I'm actually working with. The objects I'm working with have many more properties of different types, so maybe I've left out what's actually causing the problem, but I wanted to make sure that I'm understanding things on a basic level at least.

+1  A: 

If there is a record in SuperThings with Id=1, and one record in SubThings with SubId=1, according to your mapping you have a Sub instance persisted, so NHibernate is right when it tries to instantiate it.

If this is not what you intended, you should reread Chapter 8. Inheritance Mapping to see the alternatives.

Diego Mijelshon