Sebastian Hoffback
Sebastian Hoffback

Reputation: 557

NHibernate: Mapping a join on a joined table

I have a view joining 3 tables together in a chain that i need to replace with a NHibernate mapping without any changes to the database. Is this possible? This is a simplified example of my view:

SELECT tblTable1.*,tblTable2.*,tblTable3.MyProperty FROM tblTable1
OUTER JOIN
tblTable2 ON tblTable1.Table1Key = tblTable2.Table1Key
OUTER JOIN
tblTable3 ON tblTable2.Table2Key = tblTable3.Table2Key

so basicaly we select tblTable1 and join tblTable2 this works for me in NHibernate. My problem is tblTable3. How do i join it on a property from the joined table tblTable2?

When i do the mapping like this i get a query trying to join tblTable3 on Table1Key for some reason.

<class name="MyClass" table="tblTable1">

<id name="Table1Key">
  <generator class="identity"/>
</id>

<property name="..." />

<join table="tblTable2">
  <key column="Table1Key" />

  <property name="..." />
</join>

<join table="tblTable3">
  <key column="Table2Key???" />

  <property name="..." />
</join>

</class>

Upvotes: 0

Views: 5153

Answers (2)

Firo
Firo

Reputation: 30813

in NH you can't join in a join. the only way is to make it a reference, which does basicly the same thing

<class name="MyClass" table="tblTable1">
  <id name="Table1Key">
    <generator class="identity"/>
  </id>

  <property name="..." />

  <many-to-one table="tblTable2" lazy="false">
    <key column="Table1Key" />

    <property name="..." />
  </many-to-one>
</class>

<class name="MyClass2" table="tblTable2">

  <join table="tblTable3">
    <key column="Table2Key" />

    <property name="..." />
  </join>
</class>

class MyClass
{
    public virtual MyClass2 MyClass2 { get; set; }

    public virtual int MyClass2_MyProperty
    {
        get { return MyClass2.MyProperty; }
        set { MyClass2.MyProperty = value; }
    }
}

class MyClass2
{
    public virtual int MyProperty { get; set; }
}

Edit Option 2: if you dont want MyClass2 Maybe you can tweak this:

<class name="MyClass" table="tblTable2">    <-- take table2 as the main table
  <id name="Table1Key">
    <generator class="sequence">  <-- can be problem here, use sequence (directly) instead?
      <param name="sequencename">table1_id_squence</param> // not sure about "sequencename"
    </generator>
  </id>

  <property name="..." />

  <join table="tblTable1">
    <key column="Table1Key" />

    <property name="..." />
  </join>

  <join table="tblTable3">
    <key column="Table2Key" />

    <property name="..." />
  </join>
</class>

Upvotes: 1

Vasea
Vasea

Reputation: 5333

Didn't try this, but maybe you can define a property on your second join an use a property-ref for key column in your third join

  <join table="tblTable2">
    <key column="Table1Key" />
    <property name="Table2Key" />
  </join>
  <join table="tblTable3">
    <key property-ref="Table2Key" />
    <property name="..." />
  </join>

Upvotes: 0

Related Questions