简体   繁体   中英

NHibernate Mapping multiple tables to one class

In my legacy Database I have a situation like this:

TableA (id_A[PK], cod_A)
TableB (id_B[PK], cod_B, id_A[FK])
TableC (id_C[PK], cod_C, id_B[FK])

For several reasons I need to map these tables into a single class (Foo in this example)

public class Foo
{
    public virtual string IdA { get; set; }
    public virtual string CodA { get; set; }

    public virtual string IdB { get; set; }
    public virtual string CodB { get; set; }

    public virtual string IdC { get; set; }
    public virtual string CodC { get; set; }    
}

By the following mapping I'm able to join Table1 and Table2 but not Table3

<class name="Foo" table="TableA">

    <id name="IdA" column="id_A"/>
    <property name="CodA" column="cod_A"/> 

    <join table="TableB">
      <key column="id_A"/>
      <property name="IdB" column="id_B"/>
      <property name="CodB" column="cod_B"/>      
    </join>

    <!--Here my problem because off course the join will be on TableA instead on TableB-->
    <join table="TableC">
      <key column="id_B"/>
      <property name="IdC" column="id_C"/>
      <property name="CodC" column="cod_C"/>      
    </join>

  </class>

How can I map Table3?

Thanks in advance.

NHibernate discourage you to use join as much as possible. But some times there is no way around it.

The first and easiest way to solve it, if you can, is to create a view and map your class to the view.

Second way, is to create an object to each of the other tables and connect them in the proper way, probably - <one-to-one> mapping.

Third way

* Warning - proceed at your own risk *

Download NH source code - https://github.com/Nicaog/nhibernate-core/downloads .

Download the following bug patch fix instructions - https://nhibernate.jira.com/browse/NH-1681

Change the code, compile the DLL and add it to your solution.

Explanation - The patch actully fix using property-ref for <join> mapping. but also using multiple join with property-ref .

<id name="IdA" column="id_A"/>
<property name="CodA" column="cod_A"/> 

<join table="TableB">
  <key column="id_A"/>
  <property name="IdB" column="id_B"/>
  <property name="CodB" column="cod_B"/>   

  <join table="TableC">
  <key column="id_B"/>
  <property name="IdC" column="id_C"/>
  <property name="CodC" column="cod_C"/>      
  </join>
</join>

Are you able to do this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM