Hoghweed
Hoghweed

Reputation: 1948

NHibernate subclass with join table with bag of subclass problem

Hi guys I have a model of that type

public abstract class BaseEntity
{
    public Guid Id {get; set;}
}

class EntityA : BaseEntity
{
    ..other properties..
    IList<EntityB> BEntities {get; set;}
}

class EntityB : BaseEntity
{
    ..other properties..
    EntityA Owner {get, set;}
}

mapped as follow:

  <class name="BaseEntity" abstract="true" table="TBL_BaseEntity"
         dynamic-insert="true" dynamic-update="true" lazy="true" >
    <id name="Id"
        column="ID_ENTiTY"
        type="guid"
        unsaved-value="00000000-0000-0000-0000-000000000000">
      <generator class="guid.comb" />
    </id>

    <discriminator column="EtityType" type="string" force="true" />
  </class>

<subclass name="EntityA"
            extends="BaseEntity"
            discriminator-value="A"
            dynamic-insert="true"
            dynamic-update="true"
            lazy="true">

    <join table="TBL_ENTITYA">
      <key column="ID_ENTITYA" />

      ...other mapped properties...

      <bag name="BEntities" cascade="save-update"
           lazy="true" inverse="true" fetch="select" outer-join="true" >
        <key column="ID_ENTITYA" />
        <one-to-many class="EntityB"/>
      </bag>
    </join>
  </subclass>

<subclass name="EntityB"
            extends="BaseEntity"
            discriminator-value="B"
            dynamic-insert="true"
            dynamic-update="true"
            lazy="true">

    <join table="TBL_ENTITYB">
      <key column="ID_ENTITYB" />

      ...other mapped properties...

      <many-to-one name="Owner" not-null="true"
                   lazy="proxy" fetch="select" column="ID_ENTITYA" />
    </join>
  </subclass>

now the issue is when I try to insert and cascade a new EntityA with a collection of EntityB correctly initialized (in terms of the bidirectional association) everything works, but when I try to read the EntityA.BEntities collection I got an exception which states that NH could execute the query. After whatching the issue with NHProf I saw that the query produced is incorrect because NH append the column ID_ENTITYA to base table (which clearly not has that column) and not to the destination joined subclass table. Anyone can help me about this prblem? How can I avoid that behavior? It's possible to do that in NH?

Thanks in advance.

Upvotes: 1

Views: 1566

Answers (2)

mtraudt
mtraudt

Reputation: 103

I ran into the same problem recently and submitted an issue for this:

https://nhibernate.jira.com/browse/NH-2564

Upvotes: 0

Donovan
Donovan

Reputation: 11

We've just run into the same problem here, and I colleague of mine found this solution:

Create a many-to-one bi-directional relationship on EntityB back to EntityA.

This seems to help NH to figure out that the FK relationship exists between EntityA & EntityB, instead of BaseEntity & EntityB.

Hope this helps.

Upvotes: 1

Related Questions