NHibernate Mapping multiple tables to one class

百般思念 提交于 2019-12-24 02:50:06

问题


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.


回答1:


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.




回答2:


<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?



来源:https://stackoverflow.com/questions/19863668/nhibernate-mapping-multiple-tables-to-one-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!