views:

47

answers:

1

Hi,

I have a table T1 that has these columns:

  • ID (int) - is a primary Key
  • Ref (int) - (not null)
  • Name (string)

And a second table T2 with columns:

  • T2ID (int) - is a primary key
  • Value1 (int)
  • Value2 (int)
  • SomeOtherData (int)

Each record from T1 has >2 records in T2: Ref column in T1 has a value from T2 table, T2ID column.

How to write mapping file for this scenario? Currently I use this:

<class name="Class1" table="T1" >
    <id name="ID" column="ID">
        <generator class="increment"/>
    </id>
    <property name="Name"/>

        <set name="Data" inverse="true" fetch="select">
            <key>
                <column name="T2ID"/>
            </key>
            <one-to-many class="Class2"/>
        </set>
</class>

<class name="Class2" table="T2" >
    <id name="ID" column="T2ID">
        <generator class="increment"/>
    </id>
    <property name="Value1"/>
    <property name="Value2"/>
    <property name="SomeOtherData"/>
</class>

in code I have this to load T2 data for T1:

NHibernateUtil.Initialize( class1.Data );

Which generates this SQL:

SELECT 
T2ID, Value1, Value2, SomeOtherData
FROM T2
WHERE T2ID = <**an ID column from T1 for which I'm loading T2 data!**>

The problem is how to tell nHibernate to use a value from Ref column to load Data property, not PK?

Cheers, Alex

+1  A: 

As far as I know, this isn't supported. The property-ref element allows you to map this type of relationship from the "many" side but there's no equivalent for mapping the "one" side.

A workaround is to create a view for T1 that includes T2ID and map that instead of the table.

Jamie Ide
A problem is that I will have to update both of these tables... I was aware of this, but it seems I will have to use stored procedures :(
LucID
What database are you using? SQL Server, and probably others, allow for inserts and updates to views if they have a PK.
Jamie Ide
We're using SQL Server 2005 SP3, but are looking into SQLLite replacement.Found a solution which is not so good, but at least it works:Created a table T3 that has one column - T3ID, Ref in T1 is a FK for T3.T3ID column, T3ID is the same data that T2 table has in T2ID column.Class1 has a BaseData property which wraps T3 table and BaseData has Data property.
LucID

related questions