如何使用共享列将复合ID和多个映射到多个(多列)

时间:2012-03-18 14:44:29

标签: nhibernate nhibernate-mapping many-to-one composite-primary-key

我在大型旧数据库中的复合ID和多列之间的共享列有多对一关系的问题。我已将问题简化为下面的映射,以重现问题:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="Alfa">    
    <composite-id name="AlfaId" class="AlfaCompositeId">
      <key-many-to-one name="Bravo" class="Bravo" column="BRAVO_ID" />
      <key-property name="CharlieId1" column="CHARLIE_ID1" />
    </composite-id>
    <many-to-one name="C" class="Charlie">
      <column name="CHARLIE_ID1" />
      <column name="BRAVO_ID" />
    </many-to-one>
    <property name="CookieA" column="COOKIE_A" />
    </class>
  <class name="Bravo">
    <id name="BravoId" column="BRAVO_ID" />
    <property name="CookieB" column="COOKIE_B" />
  </class>
  <class name="Charlie">
    <composite-id>
      <key-property name="CharlieId1" column="CHARLIE_ID1" />
      <key-many-to-one name="Bravo" class="Bravo" column="BRAVO_ID" /> <!-- Reused column !!! -->
    </composite-id>
    <property name="CookieC" />
  </class>
</hibernate-mapping>

尝试保存Alfa实体将抛出:

IndexOutOfRangeException (Message=Invalid index 3 for this SqlParameterCollection with Count=3).

NHibernate试图两次添加BRAVO_ID列值。一次是复合id,一次是多对一FK。

如何更改映射XML以告诉NHibernate忽略&#39; BRAVO_ID&#39;柱吗

任何提示赞赏。

1 个答案:

答案 0 :(得分:0)

你映射了与CompositeId和ManyToOne相同的列,只是摆脱了compositeId

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <class name="Alfa">    
    <composite-id>
      <key-many-to-one name="Charly" class="Charlie">
        <column name="CHARLIE_ID1" />
        <column name="BRAVO_ID" />
      </key-many-to-one>
    </composite-id>
    <property name="CookieA" column="COOKIE_A" />
  </class>

  <class name="Bravo">
    <id name="Id" column="BRAVO_ID" />
    <property name="CookieB" column="COOKIE_B" />
  </class>

  <class name="Charlie">
    <composite-id>
      <key-property name="IdPart1" column="CHARLIE_ID1" />
      <key-many-to-one name="Bravo" class="Bravo" column="BRAVO_ID" />
    </composite-id>
    <property name="CookieC" />
  </class>
</hibernate-mapping>

并通过Property

访问它

Bavo b = alfa.Charly.Bravo;